You are on page 1of 21

MATLAB Tutorial

ECE204
Spring 2002
By Jianwei(Jay) Liu
Outline
• General discussion of MATLAB
– Matrix Laboratory
– How to access to HELP
• Simple calculations and graphs
• For, while, if, and relations
• M-files
• Miscellaneous
– Output format
– Colon notation
– Efficiency in Matlab
Access to Help
• Command line:
help <c o m m a n d - n a m e >
• Example:
help
help pi
help fuzzy
help ans
help help
help elfun % “elfun--elementary math functions.''
Simple calculations and graphs
(1)
• Input vectors, scalars and matrices.
– Examples:
• >> a = 2
• >> x = [1;2;3]
• >> A = [1 2 3;4 5 6;7 8 0]

• A useful command is ``whos'', which displays the names of all defined


variables and their types:
• >> C = cat(3,[1,2;3,4;5,6],[7,8;9,10;11,12])

• The arithmetic operators work as expected for scalars. A


built-in variable that is often useful is Pi.
• Scientific functions, such as sine, cosine, tangent,
exponential, and logarithm are also pre-defined.
Simple calculations and graphs
(2)
• Building Matrices
– Command line input.

– Convenient matrix building functions are

• eye identity matrix


• zeros matrix of zeros
• ones matrix of ones
• diag what is diag(diag(A)) if A is a matrix [1 2 3; 4 5 6; 7 8 9] ?
• triu upper triangular part of a matrix
• tril lower triangular part of a matrix
• rand randomly generated matrix
• hilb Hilbert matrix
• magic magic square
– Matrices can be built from blocks. For example, if A is a 3-by-3 matrix, then
B = [A, zeros(3,2); ones(2,3), eye(2)] will build a certain 5-by-5 matrix.
Simple calculations and graphs
(3)
• Scalar functions
– Certain MATLAB functions operate essentially on scalars, but operate element-
wise when applied to a matrix. The most common such functions are:
– sin cos tan
– asin acos atan
– sinh cosh tanh
– exp log(natural log) rem (remainder)
– abs sqrt sign
– round floor ceil
Simple calculations and graphs
(4)
• Vector functions

– Other MATLAB functions operate essentially on a vector (row or


column), but act on an m × n matrix in a column-by-column fashion to
produce a row vector containing the results of their application to each
column. Row-by-row action can be obtained by using transpose. For
e x a m p l e , m e a n ( A ')' . A f e w o f t h e s e f u n c t i o n s a r e :
– max sum median any
– m in prod mean all
– sort std

• F o r e x a m p l e , t h e m a x i m u m e n t r y i n a m a t r i x A i s g i v e n b y m a x ( m a x ( A ))
r a t h e r t h a n m a x ( A). H i n t : T r y t h e “ h e l p m a x ” f i r s t a n d t h e n f o l l o w t h e
illustrations.
Simple calculations and graphs
(5)
• Matrix functions

– Much of MATLAB's power comes from its matrix functions. The most
useful ones are:
eig eigenvalues and eigenvectors
chol cholesky factorization ,
svd singular value decomposition , inv inverse
lu LU factorization , qr QR factorization
hess hessenberg form schur schur decomposition
rref reduced row echelon form expm matrix exponential
sqrtm matrix square root poly characteristic
polynomial
det determinant size size
norm 1-norm, 2-norm, F-norm, infinity-norm
cond condition number in the 2-norm rank rank

• MATLAB functions may have single or multiple output arguments. For


example,
y = e i g ( A ) , o r s i m p l y eig ( A ) p r o d u c e s a c o l u m n v e c t o r c o n t a i n i n g t h e
e i g e n v a l u e s o f A w h i l e [ U,D ] = e i g ( A ) p r o d u c e s a m a t r i x U w h o s e c o l u m n s
are the eigenvectors of A a n d a d i a g o n a l m a t r i x D with the e i g e n v a l u e s of A
on its diagonal. Try it!
Simple calculations and graphs
(6) 3

• Graphs 2.5

– Examples: 2

1.5

• >> x = [1;2;3;4;5];
1

• >> y = [0;.25;3;1.5;2]; 0.5

• >> plot(x,y) or 0
1 1.5 2 2.5 3 3.5 4 4.5 5

• >> plot(x,y,‘*')
– subplot 3

– title 2.5

– 3D graphs
2

1.5

• Parametric Plots 1

• >> t = (0:2*pi/100:2*pi)';
0.5

• > plot(cos(t),sin(t))
0
1 1.5 2 2.5 3 3.5 4 4.5 5
• >> axis('square')

• title - - g r a p h t i t l e ; x l a b e l -- x - a x i s l a b e l ; y l a b e l- - y-axis label;


g t e x t-- i n t e r a c t i v e l y - p o s i t i o n e d t e x t ; text-- p o s i t i o n t e x t a t s p e c i f i c
coordinates .
Simple calculations and graphs
(7)
1 1

• Subplot
0.5 0.5
– >> t = (0:.1:2*pi)';
0 0
– > > s u b p l o t( 2 , 2 , 1 )
– >> plot(t,sin(t)) -0.5 -0.5

– > > s u b p l o t( 2 , 2 , 2 ) -1 -1
0 2 4 6 8 0 2 4 6 8
– >> plot(t,cos(t))
– > > s u b p l o t( 2 , 2 , 3 ) 500 1

– >> plot(t, exp(t)) 400 0.8

– >> subplot(2,2,4) 300 0.6


– >> plot(t,1./(1+t.^2)) 200 0.4

100 0.2

0 0
0 2 4 6 8 0 2 4 6 8
Simple calculations and graphs
(8)
• 3D plots
– >> x = (0:2*pi/20:2*pi)';
– >> y = (0:4*pi/40:4*pi)';
• Next, ``spread'' these grids into two dimensions using meshgrid:

– >> [X,Y] = meshgrid (x,y);


• The effect of meshgrid is to create a vector X with the x-grid along each row, and a vector Y with the
y- g r i d a l o n g e a c h c o l u m n . T h e n , u s i n g v e c t o r i z e d f u n c t i o n s a n d / o r o p e r a t o r s , i t i s e a s y t o e v a l u a t e a
f u n c t i o n z = f( x , y ) o f t w o v a r i a b l e s o n t h e r e c t a n g u l a r g r i d :

– >> z = cos(X).*cos(2*Y);
• Having created the matrix containing the samples of the function, the surface can be graphed using
either the mesh or the surf commands (see Figures respectively):

• > > m e s h (x,y,z)


• >> surf(x,y,z)
For, while, if, and relations (1)
• MATLAB offers a variety of flow control statements like for, while and if.
The statements that we use to control the flow are called relations
• For statement
– x = []; for i =1:n, x=[x,i^2], end % n dimentional array
– x = []; for i = n:-1:1, x=[x,i^2], end % reverse order
– for i = 1:m %m × n hilbert matrix
for j = 1:n
H(i,j) = 1/(i+j-1);
end
end
H
• While statement
while relation
statements
end
– example: F o r example, for a given number a, the following will compute and
display the smallest nonnegative integer n such that 2 to the power of n is > a :
• n = 0;
• while 2^n <= a
• n = n + 1;
• end
• n
For, while, if, and relations (2)
• If statement:The statements will be executed only if the relation is true. Multiple
branching is also possible.

if relation
statements
end
– example:
if n < 0
parity = 0;
elseif rem (n,2) == 0
parity = 2;
else
parity = 1
end

• Relations : The relational operators in MATLAB are


< less than ; > greater than; <=
less than or equal ; >= greater than or equal ==
equal ; ~= not equal

– Relations may be connected or quantified by the logical operators:


& (and), | (or), ~ (not)
M-files (1)
• MATLAB can execute a sequence of statements stored in a
file. Such files are called "M-files" because they must have
an extension of ".m" for its filename. Much of your work
with MATLAB will be creating and refining M-files.
• There are two types of M-files: script files and function files .
– Question: what’s the differences?

• Save your file in your path…


M-files (2)
• Script file
– A script file consists of a sequence of normal MATLAB statements. If the file has
the filename, say, rotate.m, then the MATLAB command rotate will cause the
statements in the file to be executed. Variables in a script file are global and will
change the value of variables of the same name in the environment of the current
MATLAB session.
– Script files are often used to enter data into a large matrix; in such a
file, entry errors can be easily edited out. If, for example, one enters in
a d i s k f i l e data.m

• A = [1 2 3 4
5 6 7 8];
– t h e n t h e M A T L A B s t a t e m e n t data w i l l c a u s e t h e a s s i g n m e n t g i v e n i n
data.m t o b e c a r r i e d o u t .
• An M-file can also reference other M-files, including referencing itself
recursively.
M-file (3)
• Function files

–?
•Your Job!
– Hint: pay attentions to the [input…]
and [output…]
Miscellaneous - Output format
• While all computations in MATLAB are performed in double precision, the format of
the displayed output can be controlled by the following commands.
• format short fixed point with 4 decimal places(the default)
• format long fixed point with 14 decimal places
• format short e scientific notation with 4 decimal places
• format long e s c i e n t i f i c n o t a t i o n w i t h 1 5 d e c i m a l p l a c e s
• Once invoked, the chosen format remains in effect until changed.
• T h e c o m m a n d format compact will suppress most blank lines allowing
more information to be placed on the screen or page. It is independent of
the other format commands.
Miscellaneous - Colon Notation (1)
• Vectors and submatrices are often used in MATLAB to achieve fairly complex data
manipulation effects. "Colon notation" ( w h i c h i s u s e d b o t h t o g e n e r a t e v e c t o r s a n d
reference submatrices) and subscripting by vectors are keys to efficient manipulation
of these objects. Creative use of these features permits one to minimize the use of
loops (which slows down MATLAB) and to make code simple and readable. Special
effort should be made to become familiar with them .

• The expression 1:5 is actually the row vector [1 2 3 4 5]. The numbers need not be
integers nor the increment one. For example,

• 0.2:0.2:1.2 = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2]


• and
• 5:-1:1 = [5 4 3 2 1]

• The following statements will, for example, generate a table of sines .

• x = [0.0:0.1:2.0]';
• y = sin(x);
• [x y]
• T r y i t ! N o t e t h a t s i n c e sin o p e r a t e s e n t r y - w i s e , i t p r o d u c e s a v e c t o r y f r o m t h e v e c t o r
x.
Miscellaneous - Colon Notation (2)
• The colon notation can be used to access submatrices of a matrix. For example,
A (1:4,3) is the column vector consisting of the first four entries of the third column of
A.
A colon by itself denotes an entire row or column:

• A(:,3) is the third column of A, and


• A(1:4,:) is the first 4 rows of A
• Arbitrary integral vectors can be used as subscripts:
• A(:,[2 4]) contains as columns, column 2 and 4 of A
• Such subscripting can be used on both sides of an assignment statement:
• A(:,[2 4 5]) = B(:,1:3) replaces columns 2, 4, 5 of A
• with the first three columns of B. Note that the entire
• altered matrix A is printed and assigned.
• Columns 2 and 4 of A can be multiplied on he right by the 2-by-2 matrix [1 2; 3 4]:
• A(:,[2,4]) = A(:,[2,4])*[1 2; 3 4]
• Once again, the entire altered matrix is printed and assigned.

• If x i s a n n - v e c t o r , w h a t i s t h e e f f e c t o f t h e s t a t e m e n t x = x(x:-1:1) ?
Miscellaneous - Efficiency in Matlab
• User-defined Matlab functions are interpreted, not compiled. This means roughly
that when an m-file is executed, each statement is read and then executed, rather than
the entire program being parsed and compiled into machine language . For this reason,
Matlab programs can be much slower than programs written in a language such as
Fortran or C.

• In order to get the most out of Matlab, it is necessary to use built-in functions and
operators whenever possible (so that compiled rather than interpreted code is
executed). For example, the following two command sequences have the same effect:

• >> t = (0:.001:1)';
• >> y=sin(t);
• and
• >> t = (0:.001:1)';
• >> for i=1:length(t)
• y(i) = sin(t(i));
• end
• However, on my computer, the explicit for-loop takes 46 times as long as the
vectorized sine function.
Comparing efficiency of
a l g o r i t h m s : f l o p s a n d etim e
• Two measures of the efficiency of an algorithm are the number of floating point operations
(flops) performed and the elapsed time.
• T h e M A T L A B f u n c t i o n flops keeps a running total of the flops performed. The
c o m m a n d flops(0) (not flops = 0!) will reset flops to 0. Hence entering flops(0)
im m e d i a t e l y b e f o r e e x e c u t i n g a n a l g o r i t h m a n d flops im m e d i a t e l y a f t e r g i v e s t h e f l o p
count for the algorithm.

• T h e M A T L A B f u n c t i o n clock gives the current time accurate to a hundreth of a second


( s e e h e l p c l o c k ) . G i v e n t w o s u c h t i m e s t1 a n d t2 , e t i m e (t2,t1 ) g i v e s t h e e l a p s e d t i m e
f r o m t1 t o t2 . O n e c a n f o r e x a m p l e , m e a s u r e t h e t i m e r e q u i r e d t o s o l v e a g i v e n l i n e a r
system A x = b using Gaussian elimintation as follows:

• t = c l o c k ; x = A \ b ; t i m e = e t i m e( c l o c k , t )
• You may wish to compare this time---and flop count---with that for solving the system
u s i n g x = i n v ( A )* b ; . T r y i t ! O t h e r s r e l a t e d c o m m a n d s a r e tic a n d t o c .
• It should be noted that, on timesharing machine, etime may not be a reliable
measure of the eficiency of an algorithm since the rate of execution depends on how
busy the computer is at that particular time when you execute your program.

You might also like