Matlab Tutorial 2: Matrices in Matlab


Exercise 5: Combining matrices in Matlab

Earlier we have seen how we can select parts of a matrix like rows, columns or elements and how we canreshape a matrix to other matrices or vectors. Here we will try to do it the other way aroud. Lets assemble a matrix from vectors. Start by defining the following matrices/vectors:

>> C=[ x' y1' y2']
C(:,1) % : means all rows and 1 stands for the first column.
C(2,:) % means the second row and all columns.
>> plot(C(:,1), C(:,2),C(:,1),C(:,3)), grid
>> ones(3) % Gives a quadratic matrix, with three columns and three rows
% only containing ones.
>> ones(3,5) % Same as above, but with three rows and five columns.

Now let us build some new matrices from the matrix and vectors above.

>> zeros(2) % Gives a quadratic matrix 2X2, and with zero as elements.
>> eye(3) % Gives the unity matrix with ones on the main diagonal.

Can we put together a matrix with vector, yes definitely. It works if they have the same number of rows or columns.

>> x=reshape( C,9,1) % gives a column vector.

Notice that [ A1 a1] would not have worked, but [ A1; a1] would have. The key is of course the inner product must be correct. Number of columns of A = number of rows of a1 Feel free to try other combinations of vectors and matrices.

Exercise 6: Matrix operations

Suppose we have two vectors x and y.

>> x=reshape(C,1,9) % gives a row vector.

How can we build the vectors z1 and z2 from x and y?

z1= z2=[ 1 0 3 2 5 8 ]
1
0
3
2
5
8

and

w1= 1 2 w2= 1 0 3
0 5         2 5 8
3 8

Pages: 1 2 3 4 5