Pages - Menu

Monday 8 October 2012

Defining matrices in MATLAB. Matrices commands and built-in functions in MATLAB

This article will show you how to define and manipulate matrices in MATLAB using built-in functions.


A matrix consists of a one or more rows vectors of the same lenght or one or more column vectors of the same lenght.


To define a matrix in MATLAB, each element of a row must be folowed by a space or comma and each row must be delimited by either a semi-colon or a new line.

>> A=[1 2 3;0 -2 6;8 10 14]
A =
    1      2     3
    0     -2     6
    8     10    14
>> B=[5 3 1
     12 9 10
      4 7 0]
B =
     5     3     1
    12     9    10
     4     7     0

You can easily change the value of a matrix element using MATLAB's indexing commands by typing the following in the command line:
>> A(1,2)=0
A =
    1      0     3
    0     -2     6
    8     10    14

As you can see, the second element of the first row of the matrix has now the value 0.

To extract a specific column of a matrix in MATLAB, use the semi-colon:
>> A(:,2)
ans =
     0
    -2
    10

The snippet above selects the entire second column of the A matrix previous defined and it essentially means "every row, second column".

Selecting a specific row of a matrix in MATLAB is done in a similar manner:
>> A(end,:)
ans =
    8      10      14

This will extract the entire last row of the matrix.

Accessing a submatrix in MATLAB is done as follows:
>> A(2:3,1:2)
ans =
    0     -2
    8     10

This passage will select rows 2 to 3 and columns 1 to 2.

If you want to extract scattered elements from a matrix, you'll need to use linear indexing, that is indexing the elements of the matrix as if they were part of a long column vector.  

In the following example, each element of the matrix has the same value as its index. 
>> M=[1 5 9 13;2 6 10 14;3 7 11 15;4 8 12 16]
M =
    1   5    9   13
    2   6   10   14
    3   7   11   15
    4   8   12   16


>> M(7)
ans =
     7

To determine the number of rows and columns of a matrix, use size
>> C=[11 3 2;25 6 14]
C =
   11   3   2
   25   6  14
>> size(C)
ans =
     2    3

MATLAB has a few build-in functions you can use to create special matrices.

For a matrix with all its elements having the value zero, use zeros.
>> zeros(2,2)
ans =
     0   0
     0   0

For a matrix with all its elements having the value one, use ones.
>> ones(2,3)
ans =
     1   1   1
     1   1   1

To create a m x n identity matrix, use the eye command.
>> I=eye(3)
I =
    1   0   0
    0   1   0
    0   0   1

For a diagonal matrix, first define a vector containing the elements on the diagonal of the matrix, then use diag.
>> d=[1 2 3]
d =
    1   2   3
>> diag(d)
ans =
      1   0   0
      0   2   0
      0   0   3

For a similar article on vectors, see this article.

No comments:

Post a Comment