- Matlab - https://matlab.diyez.net -

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 [1]. 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 [2] this can be written for a matrix A.

A=
1 2 3
4 5 6
>> A= [ 1 2 3; 4 5 6 ] % semicolon separates rows.

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:

A(row_index, column_index)

For instance try the following :

>> A(2,1)+A(2,3)+A(1,1) % adds three elements in A

or

>> A(1,1)=10 + A(2,2)

The most common matrix in matlab is the two-dimensional one. Many of the commands in matlab are only for valid for such matrices [3]. 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:

>> x=[ 5 -4 6]

or alternatively

>> x(1)=5; x(2)=-4; x(3)=6;

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.

>> x(1)=5; x(2)=-4; x(3)=6;x(5)=7

Could we now ask for element x(4) ? We have already created vectors with different lengths. And where the elements are equally spaced as:

>> x=1:1:100 % creates a vector from value 1,2 ,3, 4, 5,...100
% gives us , x=start value: spacing: final value
>> x=linspace(1,10) % creates a vector with 100 elements (default)
%  linearly spaced values from 1 to 10.
>> y=3:8 % gives a vector with integers from 3 to 8. Default step size is 1.

Sometimes you need to pick some of the elements in a vector and create a new one. There are some useful commands to achieve this. First let us create a vector with 50 random elements, in the range from 0 to 1.

>> x=rand(1,50); % rand is a random function generating numbers 
% between 0 and 1. Mean value of x should be close to 0.5 .

Now choose the elements: 12 to 15 in the vector x.

>> y= x(12:15) % Check that we picked the right elements and 
% the correct numbers by selecting x in workspace. 
% Open the vector x by double clicking->Array editor.

If we would like to decrease the number of elements in the vector we can simply use the array editor and choose the indices that we want to eliminate or by assigning certain indices to become empty. Like:

>> x(25:28)=[] % Indices 25 to 28 are eliminated.
>> x(25.28)=0 % Indices 25 to 28 are assigned to zero.
>> randn(1,500) % Creates a random vector with normal distribution,
% mean zero, variance one and standard deviation one.
% X is a row vector, that is 1 row and 500 columns.

Exercise 2: Arithmetical operations on vectors

Arithmetic operations can be performed on matrices, but in some cases they are carried out as element by element operations. Let us show you some examples:

>> A=[ 1 2; 3 4]; B=[ 1 2; 3 4];

The traditional operations like addition and subtraction assumes the same size of the matrices. As you can see below addition and subtraction is done between the corresponding elements in matrix A and B.

>> A+ B

ans=
2 4
6 8

and

>> A-B
ans=
0 0
0 0

For the operations /, * and ^ we must be cautious. Because they have a meaning as well as for the matrix as for the elements. Note the following:

>> A*B % matrix multiplication
ans =
7 10
15 22
>> A.*B % multiplication of corresponding elements in matrix A and B.
ans =
1 4
9 16
>> A/B % matrix division gives identity matrix.
ans =
1 0
0 1
>> A./B % division between the corresponding elements in matrix A and B.
ans =
1 1
1 1

and finally:

>> A.^B % each element in A 
%raised to power of the corresponding element in B.
ans =
1 4
27 256

It is of course possible to multiply a matrix by a scalar. This means what ?

>> 2*A

Get aquatinted with the commands in the table below to calculate the following for the matrix

A=[ 1 2 3; 4 5 6; 7 8 9];
  1. sum of all elements in the matrix A. % answer=45
  2. product of all elements in the matrix A. % answer=362 880
  3. the largest element in the matrix A % answer= 9
  4. the smallest element in the matrix A % answer= 1

Elementary commands operating on matrices.

 

Exercise 3: More operations with matrices

Write a simple m-file that produces a table containing one column with x-values and two others with square root values and square respectively. Below is a skeleton of m-file, but you should try to finish it.

% exercise 3.m created by MatlabCorner.com
% The m-file creates a table with: x, sqrt(x), x^2.
clear % clear all variables from workspace.
x=1:5 % creates a vector with elements 1,2,3,4 and 5
y1=...............
y2=..............
disp('x sqrt(x) x^2') % writes the text within the parenthesis.
disp([x' y1' y2']) % makes a table of three columns
% from three transposed vectors.

Plot columns two and three versus the x-vector.

>> plot(x,y1,x,y2), grid % plots two curves.

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.

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:

>> A1=[ -2 3 4; 0 -2 5; 4 3 1];
>> a1=[ 3 4 5]
>> a2=[ 5 6 7]
>> b1=[ 1; 3; 5]
>> b2=[ 8; 5; 3]

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

>> a=[ a1 a2] % two row vectors put together.
a=
3 4 5 5 6 7
>> b=[ b1 b2] % two column vectors put together.
b=
8
5
3

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

>> A1b1=[ A1 b1] %
A1b1=
-2 3 4 1
0 -2 5 3
4 3 1 5

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 = y=
1 2
0 5
3 8

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

Exercise 7: Matrix multiplication in Matlab

Matrix multiplication as you recognize them from different mathematical or applied courses are separated from element to element multiplication which we talked about earlier. The same goes for matrix division. Assume we have an equation system like:

1w + 3y + 5z = 1
1w + 0y + 1z = 0
5w + 0y + 9z = 1

Collect the coefficients to the left of the equality sign in a matrix A and the coefficients to the right in a column vector b. Then we will have an equation looking like:

AX = b, where X is a column vector containing the unknown w, y and z.

A= and b=
1 3 5 1
1 0 1 0
5 0 9 1

This can mathematically be written like: A-1AX = A-1b where A-1A = I. I stands for the identity matrix.

Therefore we have: X = A-1b

The equation can easily be solved in Matlab by:

>> X=inv(A)*b or X= A^(-1)*b % inv(A) takes the inverse of the matrix A.
% Note A must be quadratic

What will the solution be for our equation system? Please check the solution.

The scalar product of two vectors (they must have the same length). Define the following:

>> x=[ 1 0 1], y=[ 3 2 1]
>> dot( x,y) % or dot(y,x) calculates the scalar product.

If two vectors are orthogonal to each other their scalar product is zero. The product comes from element wise multiplication and then addition of the resulting elements.

>> sum(x.*y) % gives the scalar product as well.

or in this specific case as:

>> x*y' % yet, another way of calculating the scalar product.
>> C = cross(A,B) % returns the cross product of the vectors A and B.
% That is, C = A x B. A and B must be 3 element vectors.

Relation Matlab contains the possibility of comparing matrices. You can compare a matrix with a scalar. Matlab have 6 boolean operators for comparision. Relation operators:

If we use these operators there will be a new matrix as a result, containing zeros or ones. One means that the relation is true for that element, otherwise zero.

Exercise 8: Comparing matrices in Matlab

Introduce two new vectors A and B. See below !

>> A=[ 1 2 3; 3 2 1; 2 3 4]

and

>> B=2*eye(3)

Evaluate the following:

>> A==B
>> A~=B
>> A>=B

Logical operations We also have logical operators in matlab working with matrices and that results in new matrices.

Practice the operators above.

Another very useful command is find. You can use it to locate elements in the matrix which are greater than or less than a certain value.

Example:

>> [row, column]=find (B) % gives row and column indices for those elements
% which are greater than 0.
>> [row, column]=find (1.1 > A > 0.9)% gives us row and column 
% indices for those elements less than 1.1 and greater than 0.9.
row= column= % A(1,1) and A(2,3) satisfies the conditions.
1 1
2 3
[row, column, value]=find(A==1) % gives us which elements are equal to 1.
row= column= value=
1 1 1
2 3 1