Professional Documents
Culture Documents
Pony Lai
support@terasoft.com.tw
Course Outline
Writing Functions
Structuring Code
Creating Robust Applications
Troubleshooting Code and Improving
Performance
Advanced MATLAB
Programming Techniques
Writing Functions
1-1
Section Outline
Creating functions
Calling functions
Workspaces
Path and precedence
1-2
Increasing Automation
% Create the time base for the signal.
fs = 4000;
t = 0:(1/fs):1.5;
f0 A0 B fm
% Set the fundamental frequency of the call.
f0 = 175;
callmodel.m
% Set the additional parameters in the model.
A0 = 2; % Initial amplitude.
B = 1.5; % Amplitude decay rate.
fm = 0.65; % Frequency of the modulating envelope.
% Create the envelope
A = A0*exp(-B*t).*sin(2*pi*fm*t);
1-3
Creating a Function
1-4
Calling a Function
callmodel_fun.m
1-5
Workspaces
foo.m
42
0.7623
BlackBox
1-6
Calling Precedence
>> whale
1. Variable
2. Nested function
3. Subfunction
4. Private function
5. Class constructor
6. Overloaded method
1. whale.bi
7. File in the current directory 2. whale.mexw32
3. whale.mdl
8. File on the path 4. whale.p
5. whale.m
1-7
The MATLAB Path
>> pathtool
search
in order
1-8
Advanced MATLAB
Programming Techniques
Structuring Code
2-1
Section Outline
Private functions
Subfunctions
Nested functions
Function handles
Anonymous functions
Precedence rules
Comparison of function types
2-2
Course Example: Satellite Tracking
Private Functions
Function files in a folder named private
Accessible only from within this and the parent folder
Use case: make function specific to a project
getElevations
siderealTime precession
2-4
Private Functions
A.m C.m
B.m D.m
... ...
myplot.m
private myplot.m
private
PA directory PB directory
Accessed for parent directory only
function AA(x)
C(x);
2-5
Subfunctions
Several functions in one file
Keyword function used as delimiter
First function accessible from outside world
Others accessible only from within the same file
Use case: hide internal utility functions
function y = primaryFct(x)
Optional when
using only end
subfunctions function y = subFct1(x)
end
function y = subFct2(x)
end
2-6
Subfunctions
getElevations
Nested Functions
Functions nested inside other functions
Mark their extent using function and end
Can be called
From level immediately above
From function at same level within same parent function
From a nested function at any lower level
Access to superior function workspaces
Have their own workspace
function y = outerFct(x)
function y = innerFct(x)
end
end
2-8
Nested Functions
satelliteElevation
mainFunction
nested2
main function data
doublenested
nested function
2-9
Example: Nested Functions
function T = tax(income)
adjusted_income = max(income - 6000, 0);
T = compute_tax;
function t = compute_tax
t = 0.28*adjusted_income;
end
end
ODE solvers
f=@... >> [t,Y] = ...
ode45(f,t,f0)
Optimizers
>> xmin = ...
fminsearch(f,x0)
2 - 12
Creating and Using Function Handles
Syntax
fhandle = @functionname
Example
create fhandle = @sin;
use fhandle(arg1, arg2, ...);
0.8
0.6
0.2
-0.2
-0.4
-0.6
-0.8
-1
-4 -3 -2 -1 0 1 2 3 4
2 - 13
Example:
access to subfunction using function handle
2 - 14
Anonymous Functions
Wrapper to slightly change the function (interface)
Write @ followed by list of arguments and function call
No function name
No file necessary
function y = myfun(a,b,c)
>> f = @myfun; y = a*(b-sin(c));
2 - 16
Comparison of Function Types
Aspect Private Sub Nested Anonymous
File Yes Yes Yes No
Workspace Separate Separate Shared Depends
Access Files in Within file See page Via function
private 2-6 handle
and parent variable
folder
Typical use Project Hide Share Change of
specific utilities application function
functionality data interface
2 - 18
Advanced MATLAB
Programming Techniques
Creating Robust
Applications
3-1
Section Outline
Creating flexible function interfaces
Checking for warning and
error conditions
Working with the try-catch construct
and Mexception objects
x
function f = myfun(x, y, z)
3-2
Setting Default Function Inputs
function [alt,t] = getElevations(tspan,dt,doplot)
[doplot = true]
3-3
Warnings and Errors
>> elv = getElevations(1,5/1440);
getElevations.m
problem
created
problem
encountered
>> [1 2]*[3 4]
??? Error using ==> *
Inner matrix dimensions must agree.
>> foo(1)
??? Error using ==> foo
Not enough input arguments.
elv = getElevations([t0,t0+1],5/1440);
Argument Checking
3-8
Example: Input Argument Checking
function c = testarg1(a, b)
if (nargin == 1)
c = a .^ 2;
elseif (nargin == 2)
c = a + b;
end
>> testarg1(1)
ans =
1
>> testarg1(1,2)
ans =
3
3-9
Flexible Interfaces
40
20
Elevation [deg.]
-20
-40
-60
-80
-100
12:00 18:00 00:00 06:00 12:00 18:00
Time
3 - 10
Parsing Property-
Property-Value Lists
elv = getElevations([t0,t0+1],5/1440,'Width',2,'Color','r');
1 2 3 4 ...
Width 2
3 - 11
Variable Number of Inputs and Outputs
The varargin and varargout functions let you
pass any number of inputs or return any number
of outputs to a function.
Fixed number of inputs and outputs:
function [u,v] = myfun(x,y,z)
Variable number of inputs and outputs:
function [u,v] = myfun(varargin)
function varargout = myfun(x,y,z)
function [u,varargout] = myfun(x,y,varargin)
function varargout = myfun(varargin)
function
error check
The MException Object
function
try
!
run code
catch MExc
sort out
errors
end
3 - 14
Advanced MATLAB
Programming Techniques
Troubleshooting
Code and Improving
Performance
4-1
Section Outline
Generating reports on multiple files
Finding potential problems in code
Debugging code
Assessing code performance
4-2
Directory Tools
getRiseTimes
4-3
Analyzing Code in the Editor
M-Lint messages
display while you
work in the Editor
Red underline
indicates code will
have a syntax or
run-time error
(must fix)
Orange underline
indicates a variety
of M-Lint warnings
(investigate)
4-4
Resolving Dependencies
siderealTime precession
4-5
Entering Debug Mode
>> tr = getRiseTimes([t0,t0+1],5/1440)
Error using fzero (line 274)
The function values at the interval endpoints must differ in sign.
dbstop
>> tr = getRiseTimes([t0,t0+1],5/1440)
49 t0 = fzero(@satelliteElevationWrapper,t(k-1:k));
K>>
4-6
Examining Values
K>> dbstack
In fzero at 274
> In getRiseTimes at 49
4-7
Diagnosing Performance
>> tic; tr = getRiseTimes([t0,t0+1],5/1440,false); toc
algorithm 1
algorithm 2
4-9
MATLAB Profiler
or ?
siderealTime precession
4 - 10
Preallocation of Memory
A = zeros(1,N);
for J = 1:N for J = 1:N
A(J) = f(J); A(J) = f(J);
end end
4 - 11
Preallocation
x(1) = 1 x 1
x(2) = 2 x 1 x 1 2
x(3) = 3 x 1 2 x 1 2 3
x = zeros(1, 10)
x 0 0 0 0 0 0 0 0 0 0
x(10) = 10
x 0 0 0 0 0 0 0 0 0 10
4 - 12
Preallocation (Continued)
Cell Array
>> C = cell(1,5)
Structure Array
>> S(5).field1 = 1;
>> S(5).field2 = 2;
4 - 13
Vectorization
for k = 1:n
d(k) = sqrt((x(k)-x0)^2 + (y(k)-y0)^2);
end
48
46
44
42
40
38
36
5 10 15 20
d = sqrt((x-x0).^2 + (y-y0).^2);
4 - 14
Vectorizing and Memory
4 1
4 1 2 3
5 > 4
5 > 4 5 6 ? bsxfun
6 7
6 7 8 9
4 2
repmat 5 > 5
6 8
4 4 4 1 2 3 4 3
5 5 5 > 4 5 6 5 > 6
6 6 6 7 8 9 6 9
4 - 16
Optimizing File I/O
4 - 17
Memory Anatomy
Data Executables
Libraries Free Space
>> memory
Maximum possible array: 804 MB (8.431e+008 bytes) *
Memory available for all arrays: 1273 MB (1.335e+009 bytes) **
Memory used by MATLAB: 512 MB (5.367e+008 bytes)
Physical Memory (RAM): 3070 MB (3.219e+009 bytes)
4 - 18
Q&A