a mini course on matlab - matlab basics, matrix algebra and

30
A Mini course on MATLAB MATLAB Basics, Matrix Algebra and Scripting Arun K. Tangirala 1 1 Department of Chemical Engineering Indian Institute of Technology Madras Mini Course on MATLAB A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 1 / 30

Upload: hoangtram

Post on 07-Feb-2017

252 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

A Mini course on MATLABMATLAB Basics, Matrix Algebra and Scripting

Arun K. Tangirala1

1Department of Chemical EngineeringIndian Institute of Technology Madras

Mini Course on MATLAB

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 1 / 30

Page 2: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

About MATLAB

About MATLAB

“MATLAB is a high-performance language for technical computing. Itintegrates computation, visualization, and programming in an easy-to-useenvironment where problems and solutions are expressed in familiarmathematical notation. ” - from Mathworks

MATLAB is available on all three major operating systems

SIMULINK, a powerful simulator for modelling and simulatingdynamic systems, usually accompanies MATLAB (requires separateorde)

One of the biggest advantages of using MATLAB is one does notneed to declare ahead of time, the type of variable being used

The base version of MATLAB/SIMULINK is aptly supported by avariety of toolboxes

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 2 / 30

Page 3: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Outline

1 Matrices

2 Matrix manipulations

3 Graphics

4 General purpose commands

5 Programming basics

6 Scripts and Functions

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 3 / 30

Page 4: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Matrices

Matrices and Arrays!1 % Crea te a column v e c t o r2 xvec = [1 ; 2 ; 4 ; 5 ] ; % OR3 xvec = [1 2 4 5 ] ’ ; % Not i c e the t r a n s p o s e4

5 % One cou ld a l s o c r e a t e a un i f o rm l y spaced v e c t o r6 uvec = ( 0 : 0 . 0 1 : 9 9 9 . 9 9 ) ’ ; % This v e c t o r has 1000 samples7

8 % Now how to c r e a t e a mat r i x9 A = [1 2 ; 4 5 ] ;

10 % OR a s s i g n each e l ement11 A(1 , 1 ) = 1 ; A(2 , 1 ) = 2 ; A(1 , 2 ) = 4 ; A(2 , 2 ) = 5 ;12 % OR13 A = zeros ( 3 , 3 ) ;14 A(1) = 1 ; A(2) = 2 ; A(3) = 4 ; A(4) = 5 ;15 % Not i c e above how the mat r i x i s d e f i n e d l i k e an a r r a y" #Removing the semicolon at the end allows you to echo the output

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 4 / 30

Page 5: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Matrices

Creating matrices/arrays

Both matrices and vectors are enclosed in square brackets

Elements are accessed using the parentheses

One can always append and/or insert elements to these objects

A wide variety of manipulations are possible.

A vector is a special case of a matrix!1 % Access the f i r s t two and l a s t two e l emen t s o f uvec2 uvec ( [ 1 2 end!1 end ] )3 % Take e v e r y t h i r d e l ement o f uvec and s t o r e i t i n yvec4 yvec = uvec ( 1 : 3 : end ) ;5 % S i z e o f a mat r i x / v e c t o r & the t o t a l number o f e l ement s6 [ nrow , n co l ] = s i z e (A ) ; ne l A = numel (A ) ;7 % Conver t any mat r i x o r a v e c t o r i n t o a column v e c t o r8 Acol = A ( : ) ;" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 5 / 30

Page 6: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Matrices

Special matrices/vectors

MATLAB allows one to create a variety of special matrices that appear inseveral problems

One can even produce a large matrix containing replicates of a smallermatrix!

1 % Crea te an i d e n t i t y mat r i x2 Imat = eye ( 3 , 3 ) ; % Try eye (3 , 2 )3 % Crea te a mat r i x o f ones or z e r o s4 Amat = ones ( 3 , 3 ) ; % OR5 Amat = ones ( s i z e ( Imat ) ) ;6 % Sp e c i a l ma t r i c e s7 hadamard (2 ) % Hadamard mat r i x8 magic (3 ) % Magic mat r i x9 t o ep l i t z ( [ 3 4 ] , [ 3 2 ] ) % To e p l i t z mat r i x

10 % Rep l i c a t e a sma l l ma t r i x11 A = randn ( 2 , 2 ) ; B = repmat (A , 2 , 3 ) ;" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 6 / 30

Page 7: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Matrices

Simple checks on matrices/arrays

In some situations, it becomes necessary to make some important checkson the matrices of interest!1 % Check i f a mat r i x i s empty2 A = [ ] ; isempty (A)3 % Check i f two ma t r i c e s a r e equa l4 A = exp ( [ 1 2 ; 3 4 ] ) ; B = expm ( [ 1 2 ; 3 4 ] ) ;5 i s e q u a l (A,B)6 % Check i f a mat r i x c o n t a i n s numer ic e l ement s7 A = [ ’ red ’ ; ’ b lue ’ ] ; % Not i c e the t r a i l i n g space a f t e r r ed8 i s n ume r i c (A)9 % Check i f a mat r i x c o n t a i n s r e a l e l ement s

10 A = ones ( 2 , 2 ) ; B = zeros ( 2 , 2 ) ; C = A + j "B;11 i s r e a l (C)12 i s r e a l ( complex (A) )13 % Check i f ma t r i x e l ement s a r e NaN14 A = [1 2 ; i n f 4 ] ;15 i snan (A)" #A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 7 / 30

Page 8: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Matrices

Simple matrix operations

Several operations can be carried out using simple commands!1 % Transpose a mat r i x2 A = [1 2 3 ; 4 0 9 ] ; A ’3 A = [1 2 + 3 i ; 3 4 ! 5 i ] ; A ’4 % F l i p a mat r i x5 A = [1 2 3 ; 4 5 6 ] ; f l i p ud (A)6 f l i p l r (A)7 % Ex t r a c t t r i a n g u l a r p a r t8 t r i l (A)9 % Find i n d i c e s o f z e r o e l ement s

10 f i nd (A)11 f i nd (A >= 4)12 % Crea te a 3D mat r i x s t a r t i n g from a 2D mat r i x13 A = [1 2 ; 3 4 ] ; A ( : , : , 2 ) = [5 6 ; 7 8 ]14 % Remove s i n g l e t o n d imens ion15 squeeze ( rand ( 3 , 2 , 1 ) )" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 8 / 30

Page 9: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Matrix manipulations

Mathematical operations on matrices

We now learn how to perform some important mathematical operations!1 % Matr i x m u l t i p l i c a t i o n s2 A = [1 2 3 ; 4 6 8 ] ; B = randn ( 2 , 2 ) ; A"B % Regu l a r p roduc t3 A = [1 2 ; 3 4 ] ; B = [5 6 ; 7 8 ] ; A."B % Element!wi s e m u l t i p l i c a t i o n4 % Find the maximum and minimum5 A = [ 3 . 5 !3.56; 2 !1]; max(A)6 min ( abs (A) )7 % Find the i n v e r s e and de t e rm inan t o f a mat r i x8 A = [1 2 ; 4 6 ] ; inv (A)9 A = [1 3 5 ; 2 4 6 ] ; det (A’"A)

10 pinv (A) % Pseudo! i n v e r s e o f A11 % Norm and t r a c e o f a mat r i x12 A = [1 2 ; 3 4 ] ; norm (A)13 norm (A, i n f )14 trace (A) % Trace o f a mat r i x15 sum( diag (A) ) % This shou l d equa l t r a c e" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 9 / 30

Page 10: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Matrix manipulations

Mathematical operations on matrices continued!1 % Matr i x d i v i s i o n ( r e g u l a r and element!wi s e )2 A = [1 2 ; 3 4 ] ; B = [5 6 ; 7 8 ] ; B/A3 B" inv (A)4 B./A5 % Eig en va l u e c a l c u l a t i o n s6 A = [1 2 ; 3 4 ] ; [VA, lamA ] = e ig (A)7 inv (VA)"expm( lamA)"VA8 expm(A)9 % Rank o f a mat r i x

10 rank ( [ 4 5 ; 12 15 ] )11 % Ch a r a c t e r i s t i c equa t i on12 cpA = poly ( [ 1 2 ; 3 4 ] ) ;13 roots ( cpA ) % Compare wi th e i g e n v a l u e s o f A14 % LU f a c t o r i z a t i o n15 [ L ,U] = l u ( [ 1 2 ; 3 4 ] )16 % Or t h o g on a l i z a t i o n17 Q = orth ( [ 1 2 ; 3 4 ] )" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 10 / 30

Page 11: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Matrix manipulations

Special numbers and variables

pi : The number !

eps : Floating point relative accuracy

inf : The number # (too large a number)

i : The imaginary number i =$!1 (could use j)

NaN : Not-a-Number (e.g., addition or subtraction of Inf)

ans : The most recent answer

end : The last element of a vector; OR to indicate the end of a loop or a

conditional statement

all : A function that returns 1 if none of the elements of a vector are

zero; used with clear command to clear all variables

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 11 / 30

Page 12: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Matrix manipulations

Elementary functions

Trigonometric: sin, sinh, atan, sec, etc.

Exponential: exp, log2, pow2, nextpow2, sqrt, etc.

Complex: abs, angle, conj, imag, unwrap, etc.

Rounding: fix, floor, ceil, mod, rem, sign, etc.

Specialized: bessel, beta, erf, dot, gamma, etc.

Number theoretic: factor, primes, factorial, gcd, nchoosek, etc.

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 12 / 30

Page 13: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Matrix manipulations

Examples!1 % Crea te 1000 samples o f a s i n e and c o s i n e2 x = cos (2" p i " 0 . 2 " ( 0 : 9 9 9 ) ) ; y = s i n (2" p i " 0 . 2 " ( 0 : 9 9 9 ) ) ;3 f i nd ( ( x . ˆ2 + y . ˆ 2 ) ˜= 1) % Sum squa r e s shou l d equa l 14 % Crea te a complex number5 z = x + i "y ; i s r e a l ( z + conj ( z ) )6 a rgz = unwrap ( angle ( z ) ) ;7 % Rounding8 v = [ 1 . 0 0 3 2 .04 !3 .41 ] ; round ( v )9 c e i l ( v )

10 s ign ( v )11 % Genera te p r imes12 pr imes (10)13 % Find dot p roduc t14 v1 = ( 1 : 4 ) ; v2 = sqr t ( v1 ) ;15 dot ( v1 , v2 )16 sum( v1 ." v2 )" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 13 / 30

Page 14: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Graphics

Graphics

We now turn to learning how to plot data and modify the resulting plots!1 % Crea te the t ime v e c t o r and s i n e v e c t o r2 t v e c = ( 0 : 0 . 0 1 : 9 9 ) ’ ;3 x t = s i n (2" p i "0 .2" t v e c ) ;4 % Plo t the f i r s t 20 samples o f s i n e5 p lot ( t v e c ( 1 : 2 0 ) , x t ( 1 : 2 0 ) ) ;6 % Give a t i t l e and l a b e l s , and tu rn the g r i d on7 t i t l e ( ’ Plot o f f i r s t 20 samples o f s i nu s o i d ’ ) ;8 x l abe l ( ’ Samples ’ ) ; y l abe l ( ’ Amplitude ’ ) ;9 gr id on

10 % Also p l o t a c o s i n e o f the same f r e qu en c y wi th a red l i n e11 y t = cos (2" p i "0 .2" t v e c ) ;12 hold on % Hold the c u r r e n t f i g u r e13 p lot ( t v e c ( 1 : 2 0 ) , y t ( 1 : 2 0 ) , ’ r ’ ) ;" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 14 / 30

Page 15: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Graphics

Subplots

One can draw di!erent figures in di!erent plots but on the same figure!!1 t v e c = l i n space ( 0 . 0 1 , 4 , 4 0 0 ) ; % Crea te a l i n e a r l y spaced t ime v e c t o r2 % Crea te a new f i g u r e3 f i gu r e4 % Plo t the f i r s t cu r v e at the bottom5 subplot ( 2 1 1 ) ; % D i v i d e s the f i g u r e i n t o 2 rows and 1 column6 p lot ( tvec , log10 ( t v e c ) ) ;7 t i t l e ( ’ Parabola ’ ) ; x l abe l ( ’Time ’ ) ; y l abe l ( ’ Amplitude ’ ) ;8 gr id on9 % Plo t the second cu r ve at the top

10 subplot ( 2 1 2 ) ;11 semilogx ( tvec , log10 ( t v e c ) ) ; % P lo t w i th l og10 ( t ) on x!a x i s12 t i t l e ( ’ Parabola ’ ) ; x l abe l ( ’Time ’ ) ; y l abe l ( ’ Amplitude ’ ) ;13 gr id on" #The general subplot(m,n,p) refers to the pth plot in the m % n subplots

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 15 / 30

Page 16: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Graphics

Modifying plots

Each figure has a handle which provides access to all of its properties.!1 % Crea te x and y v e c t o r s2 t = 2" p i "0 . 01" ( 0 : 9 99 ) ; x = s i n ( t ) ; y = cos ( t ) ;3 % Plo t y vs . x4 h f i g = f i gu r e ; % F i gu r e command r e t u r n s a hand l e5 p lot ( x , y , ’! ’ , ’ l i n ew id th ’ , 2 ) ; % So l i d and t h i c k l i n e6 % Modify p l o t7 gr id on ; ax i s squa r e % Use squa r e a x i s to s e e the

c i r c l e8 set ( h f i g , ’ Color ’ , [ 1 1 1 ] , ’Name ’ , ’Famous Id en t i t y ’ ) ;9 h ax = gca ; % Get hand l e to c u r r e n t a x i s

10 set ( h ax , ’ f o n t s i z e ’ , 12 , ’ f ontwe ight ’ , ’ bold ’ ) ;11 % Set l a b e l s and t i t l e w i th d e s i r e d f on t12 x l abe l ( ’ x : s i n (\ theta ) ’ , ’ f o n t s i z e ’ , 14) ;13 y l abe l ( ’ y : cos (\ theta ) ’ , ’ f o n t s i z e ’ , 14) ;14 t i t l e ( ’ s i n ˆ2(\ theta ) + cos ˆ2(\ theta ) = 1 ’ ) ;15 set ( get (gca , ’ T i t l e ’ ) , ’ f ontwe ight ’ , ’ bold ’ ) ;" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 16 / 30

Page 17: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Graphics

Some tips on graphics

The get and set commands are used to retrieve the current properties

and set the desired properties of that object

The figure is the parent object, the axis its child and then the curves

are the children of the axes

There are a variety of plots possible - plot3d, contour, mesh, surf,

image, etc.

One can use LaTeX commands (see texlabel) to insert Greek

symbols

One can further change the tick labels and the tick numbers as

desired.

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 17 / 30

Page 18: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Graphics

Saving and printing

Every object in the figure can be assigned a tag.

A specific object in the figure can be easily accessed by using the

findobj command.

All figures can be edited directly by means of the GUI under Edit &Figure Properties (or type plotedit).

Figures can be saved as a MATLAB figure that can be loaded at any

later time

Every figure can exported to a variety of format including EPS, PDF

and JPG formats.

Use commands clf to clear and close the current figure.

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 18 / 30

Page 19: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

General purpose commands

General purpose commands

General: help, demo, ver, doc

Debugging: who, keyboard, disp, sprintf, return, error, debug

Workspace: whos, save, load, clear, diary, format

Editing: edit, open, pcode, which, pwd

Miscellaneous: path, pathtool, cd, copyfile, mkdir, computer, clc

Reading up the documentation and help on any function beforehand

is very useful.

MATLAB comes with a built-in editor which is very powerful. There

is also an editor which allows you to edit variables directly.

Use the clear command with caution

The keyboard and return commands are two extremely useful

commands for debugging.

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 19 / 30

Page 20: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

General purpose commands

Examples!1 % Open d i a r y to r e c o r d commands and output2 d ia ry r e c o r d . t x t3 % Crea te v a r i a b l e s i n the workspace4 A = randn ( 2 , 2 ) ; B = { ’ red ’ ; log10 (2 ) ; rand ( 2 , 1 ) } ;5 C = s t r u c t ( ’Name ’ , ’Rama ’ , ’Age ’ , 24 , ’ Place ’ , ’ Ind ia ’ ) ;6 % Check i f v a r i a b l e s have been c r e a t e d and t h e i r s i z e7 whos8 % Di s p l a y the s t r u c t u r e v a r i a b l e9 disp (C)

10 % Save them i n t o a f i l e11 save t r i a l . mat A B C12 % Cl e a r t h e s e v a r i a b l e s and then l oad them13 c l ea r a l l ;14 load t r i a l . mat15 % Ed i t mat r i x A16 open A17 d ia ry o f f % Switch o f f the d i a r y" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 20 / 30

Page 21: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Programming basics

Controlled flow!1 xvec = ( !10 : 0 . 0 1 : 1 0 ) ’ ; y f = [ ] ;2 % Begin the f o r l oop3 f o r k = 1 : length ( xvec ) ,4 i f ( x ( k ) < 0) ,5 y f ( k ) = 2"x ( k )ˆ2 + 3 ;6 e l s e7 y f ( k ) = x ( k ) + 3 ;8 end9 end

10 % Try u s i n g wh i l e l oop11 count = 1 ; yw = [ ] ;12 whi le ( count <= length ( xvec ) )13 i f ( x ( count ) < 0) ,14 yw = [ y 2"x ( count )ˆ2+3] ;15 e l s e16 yw = [ y x+3] ;17 end18 count = count + 1 ;19 end20 % Check i f both r e s u l t s a r e equa l21 i s e q u a l ( y f , yw ) ;" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 21 / 30

Page 22: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Programming basics

Controlled flow using switch

Here, we do the same task using switch command.!1 x = ( !10 : 0 . 0 1 : 1 0 ) ’ ; y s = [ ] ;2 f o r k = 1 : length ( x )3 sw i t c h ( x ( k ) < 0)4 ca se 15 ys ( k ) = 2"x ( k )ˆ2 + 3 ;6 o t h e rw i s e7 ys ( k ) = x ( k ) + 3 ;8 end9 end

10 % Try u s i n g a d i f f e r e n t method11 % Use the f i n d f u n c t i o n12 i ndneg = f i nd ( x < 0 ) ; indnonneg = f i nd ( x >= 0 ) ;13 yn = [ ] ;14 yn ( indneg ) = 2"x ( indneg ) . ˆ 2 + 3 ;15 yn ( indnonneg ) = x ( indnonneg ) + 3 ;16 % Check i f both a r e equa l17 i s e q u a l ( ys ( : ) , yn ( : ) )" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 22 / 30

Page 23: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Programming basics

Useful language commands

Controlled flow: break, continue, try, catch

Evaluation: eval, feval, run, assignin,

Scripting: function, global, mfilename, nargin, varargin,

nargchk

Messaging: warning, display, fprintf,

Interactive: input, pause, uimenu

A function in MATLAB is similar to a subroutine in C. A function takesin input arguments, processes them and produces output arguments.

The variables used within the function have a limited scope. They existas long as only the function is being executed.

Global variables are useful to access variables in the function workspacefrom the regular workspace and, therefore, should be used with caution.

Commands such as input and uimenu could be used for interactivelyseeking inputs from the user.

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 23 / 30

Page 24: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Programming basics

Polynomial functons

Polynomials: poly, roots, polyval, polyfit, polyder, conv

Interpolation: interpft, interp1, spline, interp1q!1 % Crea te a po l ynom i a l2 px = poly ( [ 1 2 ] ) % Takes i n the r o o t s o f the po l ynom i a l3 % Eva l ua t e the po l ynom i a l a t x = 1 , 2 , 34 po lyva l ( px , [ 1 2 3 ] )5 % Find r o o t s o f a po l ynom i a l : x ˆ3 + 6xˆ2 + 11x + 66 x r = roots ( [ 1 6 11 6 ] ) % Takes i n the c o e f f i c i e n t s7 px = poly ( x r ) ; % Check i f you get back the same answer8 % Convo lve po l y n om i a l s ( x+1) and ( xˆ2 + 5x + 6)9 gx = conv ( [ 1 1 ] , [ 1 5 6 ] ) % Prov i d e the c o e f f i c i e n t s

10 % F i t t i n g po l ynom i a l to data11 xk = ( 0 : 0 . 0 1 : 9 9 ) ’ ;12 yk = xk .ˆ2 + 5" xk + 0.1" randn ( length ( xk ) , 1 ) ;13 [ c e s t , s e s t ] = p o l y f i t ( xk , yk , 2 )" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 24 / 30

Page 25: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Scripts and Functions

Script file

A script file in MATLAB is any set of MATLAB commands which are

executed in that sequence.

Script files have a .m extension. Use a ‘meaningful’ name for the

filename

A script file can be run by simply typing the filename without its

extension.

The scope of the variables used in a script file is the general

workspace. They can be accessed even after the execution.

A script file can contain functions which can be used within that script.

MATLAB executes the script file by interpreting every line, which

makes it somewhat slow at times.

An m-file script can be converted into a psuedo code using the pcode

command. The resulting file runs faster than the m-file.

A script file can be put on path so that it can be called from any

directory.

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 25 / 30

Page 26: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Scripts and Functions

Script file: Example!1 % SCRIPT FILE TO SOLVE A SET OF LINEAR EQUATIONS2 % So l v e A"p = b f o r p3 A = magic ( 3 ) ; b = ( 1 : 3 ) ’ ;4 p = inv (A)"b5 % A l t e r n a t i v e l y6 p2 = A \ b7 % L i n e a r e qua t i o n s a r i s e i n system i d e n t i f i c a t i o n f o r example8 % Genera te input!output data mixed wi th n o i s e9 Phi = randn ( 2 000 , 3 ) ;

10 Y = Phi "p + 0.1" randn ( 2 000 , 1 ) ;11 % Est imate the pa ramete r s u s i n g LS method12 p l s = Phi \ Y % OR13 p l s = pinv ( Phi )"Y14 % Use l e a s t s qua r e s f u n c t i o n from op t im i z a t i o n15 p l s = l s q l i n ( Phi ,Y ) ;16 % Compare the p r e d i c t e d vs . a c t u a l output17 Yhat = Phi " p l s ;18 f i gu r e19 p lot (Y, Yhat , ’ x ’ ,Y ,Y, ’ r! ’ ) ;20 gr id on ; ax i s t i g h t ; t i t l e ( ’ Pred ic ted vs . Actual ’ ) ;21 x l abe l ( ’Y ’ ) ; y l abe l ( ’Yhat ’ ) ; legend ({ ’ Pred ic ted ’ ; ’ I d e a l ’ } ) ;" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 26 / 30

Page 27: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Scripts and Functions

Function files

Every function file should begin as:

function yout = myfun(xin)

where yout and xin are generic output and input arguments of that

function

In principle, a function can be written without the output argument or

input arguments

Any comments immediately below the function declaration line and

until the next blank or declaration line will be used by the help

command to give help on that function.

The input and output variable names are dummy names. The variables

only exist as long as the function is being executed.

A function is available for execution as soon as it is saved.

Functions can be accessed by handles, which are passed on to several

other functions such as ode45, feval, etc.

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 27 / 30

Page 28: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Scripts and Functions

Function file: Simple Example!1 funct ion r s o l = quad s o l ( cvec ) ;2 % Funct i on to compute the r o o t s o f a q u a d r a t i c equa t i on3 %4 % Usage : r s o l = quad s o l ( cvec ) ;5

6 % Read the c o e f f i c i e n t s7 a = cvec ( 1 ) ; b = cvec ( 2 ) ; c = cvec ( 3 ) ;8

9 % Compute the s o l u t i o n10 r s o l = [ ] ;11 r s o l ( 1 ) = (!b + sqr t ( bˆ2 ! 4"a"c ) )/ (2" a ) ;12 r s o l ( 2 ) = (!b ! sqr t ( bˆ2 ! 4"a"c ) )/ (2" a ) ;" #

Ideally one should also describe the input and output argumentsThe output could be of any type and any in numberVariable number of input arguments could be supplied

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 28 / 30

Page 29: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Scripts and Functions

Function file: Advanced Example!1 funct ion pspec = pspe c f un ( x , p l o t o p t )2 % Funct i on to compute and p l o t the power spectrum3 % of a s i g n a l u s i n g s t anda rd and smoothed t e c hn i q u e s4 % Usage : pspec = psp e c f un ( x , p l o t o p t ) ;5

6 % Set o p t i o n a l argument i f not s u p p l i e d7 i f ( nargin == 1) , p l o t o p t = 1 ; end8 % Read the time!s e r i e s i n f o rma t i o n9 x = x ( : ) ; nsamp = length ( x ) ;

10 % Compute the raw power spectrum11 x f = f f t ( x ) ; xps raw = abs ( x f ( 1 : end / 2 ) ) . ˆ 2 ;12 f = (0 : 1/ nsamp :0.5!1/nsamp ) ’ ;13 % Compute the smoothed power spectrum14 [ xps we l ch , F ] = pwelch ( x , 2 5 6 ) ;15 % Return the output i n pspec16 pspec = s t r u c t ( ’Xpsraw ’ , [ f xps raw ] , ’ Xpswelch ’ [ F xp s we l ch ] ) ;17 % Plo t i f opted18 i f ( p l o t o p t == 1)19 f i gu r e20 subplot ( 2 1 1 ) ;21 p lot ( f , xps raw ) ; gr id on ; ax i s t i g h t22 subplot (212)23 p lot (F/(2"max(F ) ) , xp s we l ch ) ; gr id on ; ax i s t i g h t24 end" #

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 29 / 30

Page 30: A Mini course on MATLAB - MATLAB Basics, Matrix Algebra and

Scripts and Functions

Function related functions

Optimization: fzero, fsolve, fminbnd, lsqnonlin, lsqcurvefit,

linprog, etc.

Calculus: quad, ode45, pdepe, dde23, etc.

Plotting: fplot, odeplot, ezplot, ezmesh, etc.

Miscellaneous: inline, eval, argnames, formula, etc.

Most of the functions require handles of functions to be passed to

them.

The functions related to numerical integration require the

functions to return derivatives.

A.K. Tangirala (IIT Madras) Introduction to MATLAB/SIMULINK October 2010 30 / 30