How do I assign variables in matrices?

2.4k views Asked by At

I can't make matrices with variables in it for some reason. I get following message.

>>> A= [a b ;(-1-a) (1-b); (1+a) b]

error: horizontal dimensions mismatch (2x3 vs 1x1)

Why is it? Please show me correct way if I'm wrong.

1

There are 1 answers

4
patrik On

In Matlab you first need to assign a variable before you can use it,

a = 1;
b = a+1;

This will thus give an error,

clear;
b = a+1; % ERROR! Undefined function or variable 'a

Matlab does never accept unassigned variables. This is because, on the lowest level, you do not have a. You will have machine code which is assgined the value of a. This is handled by the JIT compiler in Matlab, so you do not need to worry about this though.

If you want to use something as the variable which you have in maths you can specifically express this to matlab. The object is called a sym and the syntax that define the sym x to a variable xis,

syms x;

That said, you can define a vector or a matrix as,

syms a b x y; % Assign the syms
A = [x y]; % Vector
B = A= [a b ;(-1-a) (1-b); (1+a) b]; % Matrix.

The size of a matrix can be found with size(M) or for dim n size(M,n). You can calcuate the matrix product M3=M1*M2 if and only if M1 have the size m * n and M2 have the size n * p. The size of M3 will then be m * p. This will also mean that the operation A^N = A * A * ... is only allowed when m=n so to say, the matrix is square. This can be verified in matlab by the comparison,

syms a b
A = [a,1;56,b]
if size(A,1) == size(A,2)
    disp(['A is a square matrix of size ', num2str(size(A,1)]);
else
    disp('A is not square');
end

These are the basic rules for assigning variables in Matlab as well as for matrix multiplication. Further, a google search on the error error: 'x' undefined does only give me octave hits. Are you using octave? In that case I cannot guarantee that you can use sym objects or that the syntaxes are correct.