Examples and excises codes are free for education
goals, contact me via facebook: roland.nam.5
MATLAB PROGRAMMING TECHNIQUES
Claire Chuang
Course Outline
⚫
Increasing Automation with Functions
⚫
Structuring Code
⚫
Creating Robust Applications
⚫
Debugging Code
Advanced MATLAB®
Programming Techniques
Increasing Automation
with Functions
Section Outline
⚫
Creating functions
⚫
Calling functions
⚫
Workspaces
⚫
Path and precedence
Why Use Functions?
Increasing Automation
% Create the time base for the signal.
fs = 4000;
t = 0:(1/fs):1.5;
f0 A0 B fm
% Create the harmonics.
y0 = sin(2*pi*f0*t) + ...
sin(2*pi*2*f0*t) + sin(2*pi*3*f0*t);
% 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);
% Create the call.
call = A.*y0;
% Plot the model call and listen to it.
figure
plot(t,call)
xlabel('Time')
ylabel('Amplitude')
title('{\bf Blue Whale B Call Model}')
soundsc(call,fs)
t call
callmodel.m
% Set the fundamental frequency of the call.
f0 = 175;
Creating a Function
Function
declaration:
Keyword
Output
arguments
Function
name
Input
arguments
Calling a Function
callmodel_fun.m
Workspaces
foo.m
42
0.7623
BlackBox™
Calling Precedence
>> whale
1. Variable
2. Nested function
3. Local function
4. Private function
5. Class method
6. Overloaded method
7. File in the current directory
8. File on the path
1.
2.
3.
4.
5.
whale.bi
whale.mexw32
whale.mdl
whale.p
whale.m
The MATLAB® Path
>> pathtool
search
in order
Chapter 1 Test Your Knowledge
1. Suppose the workspace contains a vector x and the function foo creates a
scalar variable also called x. What will happen to the vector x if you issue
the command >> z = foo(7)?
A.
It will change to the scalar value defined in foo.
B.
Nothing, because the two variables are of different dimensions (i.e.,
a vector cannot be changed to a scalar).
C.
Nothing, because the vector x is not passed as an argument to foo.
D.
Nothing, because foo maintains its own workspace, so there is no
name conflict.
2. Which of the following is a valid function declaration?
A.
function [x,y] = foo(a,b)
B.
function foo(a,b) = [x,y]
C.
[x,y] = function foo(a,b)
D.
[x,y] = foo[a,b]
Exercise: Shift Cipher
MATLAB
+5
MATLAB
-5
RFYQFG
Advanced MATLAB®
Programming Techniques
Structuring Code
Section Outline
⚫
Private functions
⚫
Local functions
⚫
Nested functions
⚫
Function handles
⚫
Anonymous functions
⚫
Comparison of function types
Course Example: Satellite Tracking
a
Satellite elevation relative to the horizon
getElevations
40
satelliteElevation
Elevation [deg.]
20
0
-20
-40
siderealTime
-60
-80
00:00
06:00
12:00
Time
18:00
precession
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
getRiseTimes
satelliteElevationWrapper
satelliteElevation
siderealTime
precession
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
>> cd([matlabroot '/work/examples'])
>> edit AA.m
function AA(x)
C(x);
Local functions
⚫
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
Optional when
using only
subfunctions
function y = primaryFct(x)
…
end
function y = subFct1(x)
…
end
function y = subFct2(x)
…
end
Local functions
getElevations
satelliteElevation
getRiseTimes
satelliteElevationWrapper
siderealTime
precession
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
Nested Functions
satelliteElevation
siderealTime
precession
main function data
mainFunction
nested1
nested2
doublenested
nested function
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
>> edit tax
Scope of a Variable
Using Local function
function [A,B] = sub_scope(x,y)
A = subfun1(x);
B = subfun2(y);
Using Nested Function
function T = tax(income)
adj_income = ...
max(income - 6000, 0);
T = compute_tax;
function v = subfun1(u)
v = rand(u,1);
function v = subfun2(u)
v = randn(u,1);
separate
workspaces
>> edit sub_scope
function t = compute_tax
t = 0.28*adj_income;
end
end
shared
workspaces
Creating and Using Function Handles
⚫
Syntax
fhandle = @functionname
⚫
Example
create
use
fhandle = @sin;
fhandle(arg1, arg2, ...);
function plot_fhandle(fhandle, data)
plot(data, fhandle(data));
1
0.8
>> plot_fhandle(@sin, -pi:0.01:pi)
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-4
-3
-2
-1
0
1
2
3
4