introduction to matlabmatlab_intro.pdf · 2017-06-02 · introduction to matlab 3 matlab background...
TRANSCRIPT
![Page 2: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/2.jpg)
2Introduction to MatlabIntroduction to Matlab
What is Matlab?
A software environment for interactive numerical computations
Examples: Matrix computations and linear algebra Solving nonlinear equations Numerical solution of differential equations Mathematical optimization Statistics and data analysis Signal processing Modelling of dynamical systems Solving partial differential equations And much more ...
![Page 3: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/3.jpg)
3Introduction to MatlabIntroduction to Matlab
Matlab Background
Matlab = Matrix Laboratory
Originally a user interface for numerical linear algebra routines (Lapak/Linpak)
Commercialized 1984 by The Mathworks
Since then heavily extended (defacto-standard)
![Page 4: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/4.jpg)
4Introduction to MatlabIntroduction to Matlab
Matlab environment
Commands areentered here
Commandhistory
Workspacevariables
![Page 5: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/5.jpg)
5Introduction to MatlabIntroduction to Matlab
Calculations at the Command Line
» -5/(4.8+5.32)^2ans =
-0.0488
» (3+4i)*(3-4i)
ans =
25
» cos(pi/2)
ans =
6.1230e-017
» exp(acos(0.3))
ans =
3.5470
» -5/(4.8+5.32)^2ans =
-0.0488
» (3+4i)*(3-4i)
ans =
25
» cos(pi/2)
ans =
6.1230e-017
» exp(acos(0.3))
ans =
3.5470
» a = 2;
» b = 5;
» a^b
ans =
32
» x = 5/2*pi;
» y = sin(x)
y =
1
» z = sin(pi)
z =
1.2246e-016
» a = 2;
» b = 5;
» a^b
ans =
32
» x = 5/2*pi;
» y = sin(x)
y =
1
» z = sin(pi)
z =
1.2246e-016
Results assigned to “ans” if name not specified
»cmd_line
() parentheses for function inputs
Semicolon suppresses screen output
MATLAB as a calculator Assigning Variables
1.2246e-016 ???Numbers stored in double-precision floating point format
![Page 6: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/6.jpg)
6Introduction to MatlabIntroduction to Matlab
Variable and Memory Management
Matlab uses double precision (approx. 16 significant digits)>> format long>> format compact
All variables are shown with>> who
>> whos
Variables can be stored on file>> save filename>> clear>> load filename
![Page 7: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/7.jpg)
7Introduction to MatlabIntroduction to Matlab
Working with Files & Variables
CD / PWD, LS / DIR - navigating directories
WHAT - displays the files within a directory (grouped by type)
! - invoke operating system
WHICH - identifies the object referenced by given name (function / variable)
CLEAR - remove function / variable from memory
WHOS - lists workspace variables and details (size, memory usage, data type)
SIZE - returns the size of matrix
Ref: Utility Commands
![Page 8: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/8.jpg)
8Introduction to MatlabIntroduction to Matlab
The Help System
The help command >> help
The help window >> helpwin
The lookfor command >> lookfor
» help cd
CD Change current working directory.
CD directory-spec sets the current directory to the one specified.
CD .. moves to the directory above the current one.
CD, by itself, prints out the current directory.
WD = CD returns the current directory as a string.
Use the functional form of CD, such as CD('directory-spec'),
when the directory specification is stored in a string.
See also PWD.
» help cd
CD Change current working directory.
CD directory-spec sets the current directory to the one specified.
CD .. moves to the directory above the current one.
CD, by itself, prints out the current directory.
WD = CD returns the current directory as a string.
Use the functional form of CD, such as CD('directory-spec'),
when the directory specification is stored in a string.
See also PWD.
![Page 9: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/9.jpg)
9Introduction to MatlabIntroduction to Matlab
The Help System
Search for appropriate function>> lookfor keyword
Rapid help with syntax and function definition >> help function
An advanced hyperlinked help system is launched by>> helpdesk
Complete manuals as PDF files
![Page 10: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/10.jpg)
10Introduction to MatlabIntroduction to Matlab
Vectors and MatricesVectors (arrays) are defined as>> v = [1, 2, 4, 5]
>> w = [1; 2; 4; 5]
Matrices (2D arrays) defined similarly>> A = [1,2,3;4,-5,6;5,-6,7]
![Page 11: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/11.jpg)
11Introduction to MatlabIntroduction to Matlab
The Matrix in MATLAB
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
Rows (m) 3
4
5
Columns(n)
1 2 3 4 51 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A = A (2,4)
A (17)
Rectangular Matrix:Scalar: 1-by-1 arrayVector: m-by-1 array
1-by-n arrayMatrix: m-by-n array
Matrix elements can be EITHER numbers OR characters
![Page 12: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/12.jpg)
12Introduction to MatlabIntroduction to Matlab
Any MATLAB expression can be entered as a matrix element
Entering Numeric Arrays
» a=[1 2;3 4]
a =
1 2
3 4
» b=[-2.8, sqrt(-7), (3+5+6)*3/4]
b =
-2.8000 0 + 2.6458i 10.5000
» b(2,5) = 23
b =
-2.8000 0 + 2.6458i 10.5000 0 0
0 0 0 0 23.0000
» a=[1 2;3 4]
a =
1 2
3 4
» b=[-2.8, sqrt(-7), (3+5+6)*3/4]
b =
-2.8000 0 + 2.6458i 10.5000
» b(2,5) = 23
b =
-2.8000 0 + 2.6458i 10.5000 0 0
0 0 0 0 23.0000
Row separator:semicolon (;)
Column separator:space / comma (,)
»num_array1
Use square brackets [ ]
Matrices must be rectangular. (Set undefined elements to zero)
![Page 13: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/13.jpg)
13Introduction to MatlabIntroduction to Matlab
Entering Numeric Arrays - cont.
» w=[1 2;3 4] + 5w = 6 7 8 9» x = 1:5
x = 1 2 3 4 5» y = 2:-0.5:0
y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4)
z =
0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185
» w=[1 2;3 4] + 5w = 6 7 8 9» x = 1:5
x = 1 2 3 4 5» y = 2:-0.5:0
y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4)
z =
0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185
Scalar expansion
Creating sequences:colon operator (:)
Utility functions for creating matrices.(Ref: Utility Commands)
»num_array2
![Page 14: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/14.jpg)
14Introduction to MatlabIntroduction to Matlab
Numerical Array Concatenation - [ ]
»num_cat
» a=[1 2;3 4]
a =
1 2
3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24
» a=[1 2;3 4]
a =
1 2
3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24
Use [ ] to combine existing arrays as matrix “elements”
Row separator:semicolon (;)
Column separator:space / comma (,)
Use square brackets [ ]
The resulting matrix must be rectangular.
4*a
![Page 15: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/15.jpg)
15Introduction to MatlabIntroduction to Matlab
Array Subscripting / Indexing
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
3
4
5
1 2 3 4 51 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A =
A(3,1)A(3)
A(1:5,5)A(:,5) A(21:25)
A(4:5,2:3)A([9 14;10 15])
• Use () parentheses to specify index• colon operator (:) specifies range / ALL• [ ] to create matrix of index subscripts• ‘end’ specifies maximum index value
A(1:end,end) A(:,end)A(21:end)’
![Page 16: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/16.jpg)
16Introduction to MatlabIntroduction to Matlab
Generating Vectors from functions
zeros(M,N) MxN matrix of zeros
ones(M,N) MxN matrix of ones
rand(M,N) MxN matrix of uniformly distributed random numbers on (0,1)
x = zeros(1,3)x =
0 0 0
x = ones(1,3)x =
1 1 1
x = rand(1,3)x = 0.9501 0.2311 0.6068
![Page 17: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/17.jpg)
17Introduction to MatlabIntroduction to Matlab
Operators
[ ] concatenation
( ) subscription
x = [ zeros(1,3) ones(1,2) ]x = 0 0 0 1 1
x = [ 1 3 5 7 9]x = 1 3 5 7 9
y = x(2)y = 3y = x(2:4)y = 3 5 7
![Page 18: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/18.jpg)
18Introduction to MatlabIntroduction to Matlab
Matrix Operators
All common operators are overloaded>> v + 2
Common operators are available>> B = A’>> A*B>> A+B
Note: Matlab is case-sensitive
A and a are two different variables• Transponate conjugates complex entries; avoided by>> B=A.’
![Page 19: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/19.jpg)
19Introduction to MatlabIntroduction to Matlab
Operators (arithmetic)
+ addition- subtraction* multiplication/ division^ power' complex conjugate
transpose
.* element-by-element mult
./ element-by-element div
.^ element-by-element power
.' transpose
![Page 20: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/20.jpg)
20Introduction to MatlabIntroduction to Matlab
Operators (relational, logical)
== equal~= not equal< less than<= less than or equal> greater than>= greater than or
equal
& AND| OR~ NOT
pi 3.14159265…
j imaginary unit
i same as j
» Mass = [-2 10 NaN 30 -11 Inf 31];
» all_pos = all(Mass>=0)
all_pos =
0
» each_pos = Mass>=0
each_pos =
0 1 0 1 0 1 1
» pos_fin = (Mass>=0)&(isfinite(Mass))
pos_fin =
0 1 0 1 0 0 1
» Mass = [-2 10 NaN 30 -11 Inf 31];
» all_pos = all(Mass>=0)
all_pos =
0
» each_pos = Mass>=0
each_pos =
0 1 0 1 0 1 1
» pos_fin = (Mass>=0)&(isfinite(Mass))
pos_fin =
0 1 0 1 0 0 1
1 = TRUE0 = FALSE
![Page 21: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/21.jpg)
21Introduction to MatlabIntroduction to Matlab
Math Functions
Elementary functions (sin, cos, sqrt, abs, exp, log10, round)– type help elfun
Advanced functions (bessel, beta, gamma, erf)– type help specfun
– type help elmat
![Page 22: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/22.jpg)
22Introduction to MatlabIntroduction to Matlab
Matlab Graphics
x = 0:pi/100:2*pi;y = sin(x);plot(x,y)xlabel('x = 0:2\pi')ylabel('Sine of x')title('Plot of the
Sine Function')
![Page 23: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/23.jpg)
23Introduction to MatlabIntroduction to Matlab
Multiple Graphs
t = 0:pi/100:2*pi;y1=sin(t);y2=sin(t+pi/2);plot(t,y1,t,y2)grid on
![Page 24: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/24.jpg)
24Introduction to MatlabIntroduction to Matlab
Multiple Plots
t = 0:pi/100:2*pi;y1=sin(t);y2=sin(t+pi/2);subplot(2,2,1)plot(t,y1)subplot(2,2,2)plot(t,y2)
![Page 25: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/25.jpg)
25Introduction to MatlabIntroduction to Matlab
Bar plot of a bell shaped curve
x = -2.9:0.2:2.9;
bar(x,exp(-x.*x));
![Page 26: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/26.jpg)
26Introduction to MatlabIntroduction to Matlab
Stairstep plot of a sine wave
x=0:0.25:10;
stairs(x,sin(x));
![Page 27: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/27.jpg)
27Introduction to MatlabIntroduction to Matlab
Errorbar plot
x=-2:0.1:2;
y=erf(x);
e = rand(size(x))/10;
errorbar(x,y,e);
![Page 28: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/28.jpg)
28Introduction to MatlabIntroduction to Matlab
Polar plot
t=0:.01:2*pi;
polar(t,abs(sin(2*t).*cos(2*t)));
![Page 29: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/29.jpg)
29Introduction to MatlabIntroduction to Matlab
Stem plot
x = 0:0.1:4;
y = sin(x.^2).*exp(-x);
stem(x,y)
![Page 30: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/30.jpg)
30Introduction to MatlabIntroduction to Matlab
Graph Functions (summary)
plot linear plot stem discrete plot grid add grid lines xlabel add X-axis label ylabel add Y-axis label title add graph title subplot divide figure window figure create new figure window pause wait for user response
![Page 31: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/31.jpg)
31Introduction to MatlabIntroduction to Matlab
Programming in MATLAB
![Page 32: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/32.jpg)
32Introduction to MatlabIntroduction to Matlab
Matlab environment
Matlab construction Core functionality as compiled C-code, m-files Additional functionality in toolboxes (m-files)
Matlab programming (construct own m-files)
Core m-filesC-kernel
Statistics Symb. mathpolyLX
![Page 33: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/33.jpg)
33Introduction to MatlabIntroduction to Matlab
The programming environmentThe working directory is controlled by>> dir>> cd catalogue>> pwd
The path variable defines where matlab searches for m-files
>> path>> addpath>> pathtool>> which function
![Page 34: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/34.jpg)
34Introduction to MatlabIntroduction to Matlab
The programming environment
Matlab can’t tell if identifier is variable or function>> z=theta;
Matlab searches for identifier in the following order1. variable in current workspace2. built-in variable3. built-in m-file4. m-file in current directory5. m-file on search path
Note: m-files can be located in current directory, or in path
![Page 35: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/35.jpg)
35Introduction to MatlabIntroduction to Matlab
Script files
Script-files contain a sequence of Matlab commands
%FACTSCRIPT – Compute n-factorial, n!=1*2*...*n
y = prod(1:n);
%FACTSCRIPT – Compute n-factorial, n!=1*2*...*n
y = prod(1:n);
factscript.mfactscript.m
Executed by typing its name>> factscript
Operates on variables in global workspace Variable n must exist in workspace Variable y is created (or over-written)
Use comment lines (starting with %) to document file!
![Page 36: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/36.jpg)
36Introduction to MatlabIntroduction to Matlab
Script M-files
Standard ASCII text files Contain a series of MATLAB expressions
(Typed as you would at the command line)
Commands parsed & executed in order% Comments start with "%" character
pause % Suspend execution - hit any key to continue.
keyboard % Pause & return control to command line.
% Type "return" to continue.
break % Terminate execution of current loop/file.
return % Exit current function
% Return to invoking function/command line.
% Comments start with "%" character
pause % Suspend execution - hit any key to continue.
keyboard % Pause & return control to command line.
% Type "return" to continue.
break % Terminate execution of current loop/file.
return % Exit current function
% Return to invoking function/command line.
![Page 37: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/37.jpg)
37Introduction to MatlabIntroduction to Matlab
Displaying code and getting help
To list code, use type command>> type factscript
The help command displays first consecutive comment lines
>> help factscript
![Page 38: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/38.jpg)
38Introduction to MatlabIntroduction to Matlab
MATLAB Editor/Debugger
»edit <filename>
![Page 39: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/39.jpg)
39Introduction to MatlabIntroduction to Matlab
Functions
Functions describe subprogramsTake inputs, generate outputsHave local variables (invisible in global workspace)
function [output_args]= function_name(input_args)% Comment lines<function body>function [z]=factfun(n)
% FACTFUN – Compute factorial% Z=FACTFUN(N)
z = prod(1:n);
function [z]=factfun(n)% FACTFUN – Compute factorial% Z=FACTFUN(N)
z = prod(1:n);
factfun.mfactfun.m
>> y=factfun(10);
![Page 40: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/40.jpg)
40Introduction to MatlabIntroduction to Matlab
function y = mean(x)
% MEAN Average or mean value.
% For vectors, MEAN(x) returns the mean value.
% For matrices, MEAN(x) is a row vector
% containing the mean value of each column.
[m,n] = size(x);
if m == 1
m = n;
end
y = sum(x)/m;
function y = mean(x)
% MEAN Average or mean value.
% For vectors, MEAN(x) returns the mean value.
% For matrices, MEAN(x) is a row vector
% containing the mean value of each column.
[m,n] = size(x);
if m == 1
m = n;
end
y = sum(x)/m;
Structure of a Function M-fileKeyword: function Function Name (same as file name .m)
Output Argument(s) Input Argument(s)
Online Help
MATLABCode
»output_value = mean(input_value) Command Line Syntax
![Page 41: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/41.jpg)
41Introduction to MatlabIntroduction to Matlab
Subfunctions
Allows more than one function to be within the same M-file (modularize code)
M-file must have the name of the first (primary) function
Subfunctions can only be called from within the same M-file
Each subfunction has its own workspace
![Page 42: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/42.jpg)
42Introduction to MatlabIntroduction to Matlab
Example: Subfunctions
function [totalsum,average] = subfunc (input_vector)
% SUBFUNC Calculates cumulative total & average
totalsum = sum(input_vector);
average = ourmean(input_vector); %Call to subfunction
function y = ourmean(x)
% (OURMEAN) Calculates average
[m,n] = size(x);
if m == 1
m = n;
end
y = sum(x)/m;
function [totalsum,average] = subfunc (input_vector)
% SUBFUNC Calculates cumulative total & average
totalsum = sum(input_vector);
average = ourmean(input_vector); %Call to subfunction
function y = ourmean(x)
% (OURMEAN) Calculates average
[m,n] = size(x);
if m == 1
m = n;
end
y = sum(x)/m;
»[SUM, MEAN] = subfunc(rand(1,50))
PrimaryFunction
Sub-Function
![Page 43: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/43.jpg)
43Introduction to MatlabIntroduction to Matlab
Multiple Input & Output Arguments
function r = ourrank(X,tol)
% OURRANK Rank of a matrix
s = svd(X);
if (nargin == 1)
tol = max(size(X))*s(1)*eps;
end
r = sum(s > tol);
function r = ourrank(X,tol)
% OURRANK Rank of a matrix
s = svd(X);
if (nargin == 1)
tol = max(size(X))*s(1)*eps;
end
r = sum(s > tol);function [mean,stdev] = ourstat(x)% OURSTAT Mean & std. deviation[m,n] = size(x);if m == 1
m = n;endmean = sum(x)/m;stdev = sqrt(sum(x.^2)/m – mean.^2);
function [mean,stdev] = ourstat(x)% OURSTAT Mean & std. deviation[m,n] = size(x);if m == 1
m = n;endmean = sum(x)/m;stdev = sqrt(sum(x.^2)/m – mean.^2);
Multiple Input Arguments ( , )
Multiple Output Arguments [ , ]
»RANK = ourrank(rand(5),0.1);»[MEAN,STDEV] = ourstat(1:99);
![Page 44: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/44.jpg)
44Introduction to MatlabIntroduction to Matlab
Scripts or function: when use what?
Functions Take inputs, generate outputs, have internal variables Solve general problem for arbitrary parameters
Scripts Operate on global workspace Document work, design experiment or test Solve a very specific problem once
% FACTTEST – Test factfun
N=50;y=factfun(N);
% FACTTEST – Test factfun
N=50;y=factfun(N);
facttest.mfacttest.m
![Page 45: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/45.jpg)
45Introduction to MatlabIntroduction to Matlab
Flow Control Constructs
Logic Control: IF / ELSEIF / ELSE SWITCH / CASE / OTHERWISE
Iterative Loops: FOR WHILE
![Page 46: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/46.jpg)
46Introduction to MatlabIntroduction to Matlab
Logical expressions
Relational operators (compare arrays of same sizes)== (equal to) ~= (not equal) < (less than) <= (less than or equal to)> (greater than) >= (greater than or equal to)
Logical operators (combinations of relational operators)& (and)| (or)~ (not)
Logical functionsxorisemptyanyall
if (x>=0) & (x<=10)
disp('x is in range [0,10]')
else
disp('x is out of range')
end
if (x>=0) & (x<=10)
disp('x is in range [0,10]')
else
disp('x is out of range')
end
![Page 47: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/47.jpg)
47Introduction to MatlabIntroduction to Matlab
Flow control - repetition
Repeats a code segment a fixed number of times
for index=<vector>
<statements>
end
The <statements> are executed repeatedly.At each iteration, the variable index is assigneda new value from <vector>.
for k=1:12 kfac=prod(1:k); disp([num2str(k),' ',num2str(kfac)])end
for k=1:12 kfac=prod(1:k); disp([num2str(k),' ',num2str(kfac)])end
![Page 48: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/48.jpg)
48Introduction to MatlabIntroduction to Matlab
Flow control - selection
The if-elseif-else construction
if <logical expression>
<commands>
elseif <logical expression>
<commands>
else
<commands>
end
if height>170
disp(’tall’)
elseif height<150
disp(’small’)
else
disp(’average’)
end
if height>170
disp(’tall’)
elseif height<150
disp(’small’)
else
disp(’average’)
end
![Page 49: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/49.jpg)
49Introduction to MatlabIntroduction to Matlab
Example – selection and repetition
function y=fact(n)% FACT – Display factorials of integers 1..nif nargin < 1 error('No input argument assigned')elseif n < 0 error('Input must be non-negative')elseif abs(n-round(n)) > eps error('Input must be an integer')end
for k=1:n kfac=prod(1:k); disp([num2str(k),' ',num2str(kfac)]) y(k)=kfac;end;
function y=fact(n)% FACT – Display factorials of integers 1..nif nargin < 1 error('No input argument assigned')elseif n < 0 error('Input must be non-negative')elseif abs(n-round(n)) > eps error('Input must be an integer')end
for k=1:n kfac=prod(1:k); disp([num2str(k),' ',num2str(kfac)]) y(k)=kfac;end;
fact.mfact.m
![Page 50: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/50.jpg)
50Introduction to MatlabIntroduction to Matlab
Switch, Case, and Otherwise
switch input_num
case -1
input_str = 'minus one';
case 0
input_str = 'zero';
case 1
input_str = 'plus one';
case {-10,10}
input_str = '+/- ten';
otherwise
input_str = 'other value';
end
switch input_num
case -1
input_str = 'minus one';
case 0
input_str = 'zero';
case 1
input_str = 'plus one';
case {-10,10}
input_str = '+/- ten';
otherwise
input_str = 'other value';
end
More efficient than elseif statements
Only the first matching case is executed
»switch_examp
![Page 51: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/51.jpg)
51Introduction to MatlabIntroduction to Matlab
The while loop
I=1; N=10;
while I<=NJ=1;while J<=N
A(I,J)=1/(I+J-1);J=J+1;
endI=I+1;
end
I=1; N=10;
while I<=NJ=1;while J<=N
A(I,J)=1/(I+J-1);J=J+1;
endI=I+1;
end
»while_examp
• Similar to other programming languages
• Repeats loop until logical condition returns FALSE.
• Can be nested.
![Page 52: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/52.jpg)
52Introduction to MatlabIntroduction to Matlab
Flow control – conditional repetition
while-loops
<statements> are executed repeatedly as long as the <logical expression> evaluates to true
while <logical expression>
<statements>
end
k=1;
while prod(1:k)~=Inf,
k=k+1;
end
disp(['Largest factorial in Matlab:',num2str(k-1)]);
k=1;
while prod(1:k)~=Inf,
k=k+1;
end
disp(['Largest factorial in Matlab:',num2str(k-1)]);
![Page 53: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/53.jpg)
53Introduction to MatlabIntroduction to Matlab
Flow control – conditional repetition
Solutions to nonlinear equations
can be found using Newton’s method
Task: write a function that finds a solution to
Given , iterate until
![Page 54: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/54.jpg)
54Introduction to MatlabIntroduction to Matlab
Flow control – conditional repetition
function [x,n] = newton(x0,tol,maxit)% NEWTON – Newton’s method for solving equations% [x,n] = NEWTON(x0,tol,maxit) x = x0; n = 0; done=0;while ~done, n = n + 1; x_new = x - (exp(-x)-sin(x))/(-exp(-x)-cos(x)); done=(n>=maxit) | ( abs(x_new-x)<tol ); x=x_new;end
function [x,n] = newton(x0,tol,maxit)% NEWTON – Newton’s method for solving equations% [x,n] = NEWTON(x0,tol,maxit) x = x0; n = 0; done=0;while ~done, n = n + 1; x_new = x - (exp(-x)-sin(x))/(-exp(-x)-cos(x)); done=(n>=maxit) | ( abs(x_new-x)<tol ); x=x_new;end
newton.mnewton.m
>> [x,n]=newton(0,1e-3,10)
![Page 55: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/55.jpg)
55Introduction to MatlabIntroduction to Matlab
Function functions
Do we need to re-write newton.m for every new function?
No! General purpose functions take other m-files as input.
>> help feval>> [f,f_prime]=feval(’myfun’,0);function [f,f_prime] = myfun(x)% MYFUN– Evaluate f(x) = exp(x)-sin(x)% and its first derivative % [f,f_prime] = myfun(x)
f=exp(-x)-sin(x);f_prime=-exp(-x)-cos(x);
function [f,f_prime] = myfun(x)% MYFUN– Evaluate f(x) = exp(x)-sin(x)% and its first derivative % [f,f_prime] = myfun(x)
f=exp(-x)-sin(x);f_prime=-exp(-x)-cos(x);
myfun.mmyfun.m
![Page 56: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/56.jpg)
56Introduction to MatlabIntroduction to Matlab
Function functions
),( txfdt
dx =
Can update newton.m
>> [x,n]=newtonf(’myfun’,0,1e-3,10)
function [x,n] = newtonf(fname,x0,tol,maxit)% NEWTON – Newton’s method for solving equations% [x,n] = NEWTON(fname,x0,tol,maxit) x = x0; n = 0; done=0;while ~done, n = n + 1; [f,f_prime]=feval(fname,x); x_new = x - f/f_prime; done=(n>maxit) | ( abs(x_new-x)<tol ); x=x_new;end
function [x,n] = newtonf(fname,x0,tol,maxit)% NEWTON – Newton’s method for solving equations% [x,n] = NEWTON(fname,x0,tol,maxit) x = x0; n = 0; done=0;while ~done, n = n + 1; [f,f_prime]=feval(fname,x); x_new = x - f/f_prime; done=(n>maxit) | ( abs(x_new-x)<tol ); x=x_new;end
newtonf.mnewtonf.m
![Page 57: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/57.jpg)
57Introduction to MatlabIntroduction to Matlab
Programming tips and tricks
Programming style has huge influence on program speed!
tic; x=-2500:0.1:2500;for ii=1:length(x) if x(ii)>=0, s(ii)=sqrt(x(ii)); else s(ii)=0; end;end;toc
tic; x=-2500:0.1:2500;for ii=1:length(x) if x(ii)>=0, s(ii)=sqrt(x(ii)); else s(ii)=0; end;end;toc
ticx=-2500:0.1:2500;s=sqrt(x); s(x<0)=0;toc;
ticx=-2500:0.1:2500;s=sqrt(x); s(x<0)=0;toc;
slow.mslow.m
fast.mfast.m
Loops are slow: Replace loops by vector operations!Memory allocation takes a lot of time: Pre-allocate memory!Use profile to find code bottlenecks!
![Page 58: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/58.jpg)
58Introduction to MatlabIntroduction to Matlab
Recall: Array Operations
Using Array Operations:
Using Loops:[rows, cols] = size(M);
for I = 1:rows
for J = 1:cols
Density(I,J) = M(I,J)/(L(I,J)*W(I,J)*H(I,J));
end
end
[rows, cols] = size(M);
for I = 1:rows
for J = 1:cols
Density(I,J) = M(I,J)/(L(I,J)*W(I,J)*H(I,J));
end
end
Density = Mass(I,J)/(Length.*Width.*Height);Density = Mass(I,J)/(Length.*Width.*Height);
»array_vs_loops
![Page 59: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/59.jpg)
59Introduction to MatlabIntroduction to Matlab
Summary
User-defined functionality in m-files Stored in current directory, or on search path
Script-files vs. functions Functions have local variables, Scripts operate on global workspace
Writing m-files Header (function definition), comments, program body Have inputs, generate outputs, use internal variables Flow control: ”if...elseif...if”, ”for”, ”while” General-purpose functions: use functions as inputs
Programming style and speed Vectorization, memory allocation, profiler
![Page 60: Introduction to Matlabmatlab_intro.pdf · 2017-06-02 · Introduction to Matlab 3 Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra](https://reader034.vdocuments.us/reader034/viewer/2022042515/5faac1d175308f0ff9376f25/html5/thumbnails/60.jpg)
60Introduction to MatlabIntroduction to Matlab
Advanced Matlab Programming
Functions Can have variable number of inputs and outputs
(see: nargin, nargout, varargin, varargout) Can have internal functions
Data types: more than just arrays and strings: Structures Cell arrays
File handling Supports most C-commands for file I/O (fprintf,…)