Matlab Tutorial 2: Matrices in Matlab


The command disp does not produce any fancy output in the command window. It is a simple way to write text in the same window. Later on in the course we will of course find better ways to make nice tables. Suppose now that I define a matrix C as:

>> C=[ x' y1' y2']

I can easily choose columns from this matrix and plot them versus each other.

C(:,1) % : means all rows and 1 stands for the first column.
C(2,:) % means the second row and all columns.

by writing

>> plot(C(:,1), C(:,2),C(:,1),C(:,3)), grid

we have achieved the same as the previous plot command.

Exercise 4: Special matrices in Matlab

Sometimes we need to use special matrices, like some with only zeros or ones as elements. This can easily be done by:

>> 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.
>> zeros(2) % Gives a quadratic matrix 2X2, and with zero as elements.
>> eye(3) % Gives the unity matrix with ones on the main diagonal.

Put together the following matrix by adding and scalar multiplicaton.

4 3 3
3 4 3
3 3 4

Denote the matrix as C. Reshaping matrices can also be very useful trick. Assume we would like to reshape the matrix C to a new matrix/vector. It has 3 rows and 3 columns. The new matrix or vector must of course after this operation also contain 9 elements. When we perform reshape Notice that the order of this is column by column. In this case we can only have a row vector or column vector. Think of the reason for that?

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

Check the output of these commands.

Pages: 1 2 3 4 5