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

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