Matlab Tutorial 2: Matrices in Matlab

Matrices in Matlab

In the previous tutorial we have used the concept vector. This is a special case of matrix. A two-dimensional matrix is nothing but a rectangular table with its elements ordered in rows and columns. A matrix mxn consists of m rows and n columns. In Matlab this can be written for a matrix A.

>> 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.

This matrix A has 2 rows and 3 columns. The first row is: 1 2 3 and the second: 4 5 6 . For the columns we have the have following order: Column 1: 1,4 column 2: 2,5 and finally column 3: 3,6

Each entry in the matrix A is accessible by using the following indices:

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

For instance try the following :

>> ones(3) % Gives a quadratic matrix, with three columns and three rows
% only containing ones.

or

>> ones(3,5) % Same as above, but with three rows and five columns.

The most common matrix in matlab is the two-dimensional one. Many of the commands in matlab are only for valid for such matrices. The arithmetic operators (+, -, *, / and ^) that we used in tutorial1 can also be applied for matrices, but we also have some others as well.

Exercise 1: Vectors in Matlab

Generate a vector x=[5, -4, 6 ] with three elements. In Matlab as:

>> zeros(2) % Gives a quadratic matrix 2X2, and with zero as elements.

or alternatively

>> eye(3) % Gives the unity matrix with ones on the main diagonal.

What is the answer of x(4) and x(0) ?

The indices in a vector starts from 1 and in this case ends with 3. Therefore to ask for x(4) and x(0) is pointless. Suppose we would have done differently creating the vector x. Read more »