Thursday, January 7, 2010

Working with matrices in MATLAB

MATLAB has many useful commands for creating,manipulating or operating on matrices.I hope to show you just a small sample here just to show how can matlab create any matrices.
You can create a 3 .4 matrix full of zeroes:
» A = zeros (3,4)
A=
0 0 0 0
0 0 0 0
0 0 0 0
or u can create a martrices full of ones:
» B = ones (3,4)
B =
1 1 1 1
1 1 1 1
1 1 1 1
Note that you can make a row vector full of zeros by typing zeros (1,5) or a column vector of zeros using zeros (5,1).Typing zeros (5) will give a 5.5 matris full of zeros.Perhaps more or a useful than a matrix full of ones is the identity matrix which have ones on the main diagonal and zeros elsewhere.Remember that identity matrices are always square,ao that you only need to specify the number of rows in the matrix:
» I = eye (4)
I =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Identity rows and columns of matrices
The 3rd row of a matrix can be seen in Matlab by typing:
» I(3,:)
ans =
0 0 1 0
The 3rd column can be seen i a similar fashion:
» I(:,3)
ans =
0
0
1
0
You can even select submatrices in this way.Here we pick off a 3x3 matix.
» I (1:3,2:4)
ans =
0 0 0
1 0 0
0 1 0
DIAGONALS AND TRIANGLES
i created a 4x4 random matrix:
» A = rand (4)
A =
0.9501 0.8913 0.8214 0.9218
0.2311 0.7621 0.4447 0.7382
0.6068 0.4565 0.6154 0.1763
0.4860 0.0185 0.7919 0.4057
you can select the upper part of A using
triu:
» upper = triu(A)
upper =
0.9501 0.8913 0.8214 0.9218
0 0.7621 0.4447 0.7382
0 0 0.6154 0.1763
0 0 0 0.4057
The lower triangular part may be picked off using
tril:
» lower = tril (A)
lower =
0.9501 0 0 0
0.2311 0.7621 0 0
0.6068 0.4565 0.6154 0
0.4860 0.0185 0.7919 0.4057
The main diagonal may be extracted (as a vector) using
diag:
1
» d = diag(A)
d =
0.9501
0.7621
0.6154
0.4057

3 comments:

  1. i don't think the everybody know how to use matlab but i hope the some people will try it because it is a nice program.hope you will like my post.

    ReplyDelete
  2. Thanks Mario! Matlab IS IMPORTANT!

    BUT the idea of the Blog is about REAL LIFE situations! So, if you can CHANGE your post, you still have time!

    Thanks,

    Zeina

    ReplyDelete
  3. Mario, your post is too long! Delete and change!
    Thanks, Zeina

    ReplyDelete