Introduction to Matlab
2E1215, Lecture 2 – Matlab Programming
http://www.s3.kth.se/control/kurser/2E1215/
Mikael Johansson and Frank Lingelbach
Department of Signals, Sensors, and Systems
Programming in Matlab 2
Today’s Lecture
Matlab programming
Programming environment and search path
M-file scripts and functions
Flow control statements
Function functions
Programming tricks and tips
Programming in Matlab 3
Matlab environment
Matlab construction
Core functionality as compiled C-code, m-files
Additional functionality in toolboxes (m-files)
Today: Matlab programming (construct own m-files)
Sig. Proc Contr. Syst.
User defined
C-kernel Core m-files
Programming in Matlab 4
The programming environment
The working directory is controlled by
>> dir
>> cd catalogue
>> pwd
The path variable defines where matlab searches for m-files
>> path
>> addpath
>> pathtool
>> which function
Programming in Matlab 5
The programming environment
Matlab can’t tell if identifier is variable or function
>> z=theta;
Matlab searches for identifier in the following order
1. variable in current workspace
2. built-in variable
3. built-in m-file
4. m-file in current directory
5. m-file on search path
Note: m-files can be located in current directory, or in path
Programming in Matlab 6
Script files
Script-files contain a sequence of Matlab commands
factscript.m
factscript.m
%FACTSCRIPT
%FACTSCRIPT –– Compute
Compute n-factorial,
n-factorial, n!=1*2*...*n
n!=1*2*...*n
yy == prod(1:n);
prod(1:n);
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!
Programming in Matlab 7
Displaying code and getting help
To list code, use type command
>> type factscript
The help command displays first consecutive comment
lines
>> help factscript
Programming in Matlab 8
Functions
Functions describe subprograms
Take inputs, generate outputs
Have local variables (invisible in global workspace)
[output_arguments]= function_name(input_arguments)
% Comment lines
<function body> factfun.m
factfun.m
function
function [z]=factfun(n)
[z]=factfun(n)
%% FACTFUN
FACTFUN –– Compute
Compute factorial
factorial
%% Z=FACTFUN(N)
Z=FACTFUN(N)
zz == prod(1:n);
prod(1:n);
>> y=factfun(10);
Programming in Matlab 9
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
Exam: all problems will require you to write functions
facttest.m
facttest.m
%% FACTTEST
FACTTEST –– Test
Test factfun
factfun
N=50;
N=50;
y=factfun(N);
y=factfun(N);
Programming in Matlab 10
Flow control - selection
The if-elseif-else construction
if <logical expression>
<commands>
elseif <logical expression>
if
if height>170
height>170
<commands>
disp(’tall’)
disp(’tall’)
else
elseif
elseif height<150
height<150
<commands>
disp(’small’)
disp(’small’)
end
else
else
disp(’average’)
disp(’average’)
end
end
Programming in Matlab 11
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)
if
if (x>=0)
(x>=0) && (x<=10)
(x<=10)
Logical functions
xor disp(‘x
disp(‘x is
is in
in range
range [0,10]’)
[0,10]’)
isempty
any else
else
all disp(‘x
disp(‘x is
is out
out of
of range’)
range’)
end
end
Programming in Matlab 12
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 assigned
a new value from <vector>.
for
for k=1:12
k=1:12
kfac=prod(1:k);
kfac=prod(1:k);
disp([num2str(k),’
disp([num2str(k),’
‘,num2str(kfac)])
‘,num2str(kfac)])
end
end
Programming in Matlab 13
Example – selection and repetition
fact.m
fact.m
function
function y=fact(n)
y=fact(n)
%% FACT
FACT –– Display
Display factorials
factorials of
of integers
integers 1..n
1..n
if
if nargin
nargin << 11
error(’No
error(’No input
input argument
argument assigned’)
assigned’)
elseif
elseif nn << 00
error(’Input
error(’Input must
must be
be non-negative’)
non-negative’)
elseif
elseif abs(n-round(n))
abs(n-round(n)) >> eps
eps
error(’Input
error(’Input must
must be
be an
an integer’)
integer’)
end
end
for
for k=1:n
k=1:n
kfac=prod(1:k);
kfac=prod(1:k);
disp([num2str(k),’
disp([num2str(k),’ ’,num2str(kfac)])
’,num2str(kfac)])
y(k)=kfac;
y(k)=kfac;
end;
end;
Programming in Matlab 14
Repetition: Animation demo
The function movie replays a sequence of captured frames
Construct a movie of a 360° tour around the Matlab logo
logomovie.m
logomovie.m
%% logomovie
logomovie –– make
make movie
movie of
of 360
360 degree
degree logo
logo
tour
tour logo;
logo;
no_frames=40;
no_frames=40;
dtheta=360/no_frames;
dtheta=360/no_frames;
for
for frame
frame == 1:no_frames,
1:no_frames,
camorbit(dtheta,0)
camorbit(dtheta,0)
M(frame)
M(frame) == getframe(gcf);
getframe(gcf);
end
end
%% now
now display
display captured
captured movie
movie
movie(gcf,M);
movie(gcf,M);
Programming in Matlab 15
Flow control – conditional repetition
while-loops
while <logical expression>
<statements>
end
<statements> are executed repeatedly as long as the
<logical expression> evaluates to true
k=1;
k=1;
while
while prod(1:k)~=Inf,
prod(1:k)~=Inf,
k=k+1;
k=k+1;
end
end
disp([‘Largest
disp([‘Largest factorial
factorial in
in Matlab:’,num2str(k-1)]);
Matlab:’,num2str(k-1)]);
Programming in Matlab 16
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 maxit times or until
Programming in Matlab 17
Flow control – conditional repetition
newton.m
newton.m
function
function [x,n]
[x,n] == newton(x0,tol,maxit)
newton(x0,tol,maxit)
%% NEWTON
NEWTON –– Newton’s
Newton’s method
method for
for solving
solving equations
equations
%% [x,n]
[x,n] == NEWTON(x0,tol,maxit)
NEWTON(x0,tol,maxit)
xx == x0;
x0; nn == 0;
0; done=0;
done=0;
while
while ~done,
~done,
nn == nn ++ 1;
1;
x_new
x_new == xx -- (exp(-x)-sin(x))/(-exp(-x)-
(exp(-x)-sin(x))/(-exp(-x)-
cos(x));
cos(x));
done=(n>=maxit)
done=(n>=maxit) || (( abs(x_new-x)<tol
abs(x_new-x)<tol );
);
x=x_new;
x=x_new;
end
end
>> [x,n]=newton(0,1e-3,10)
Programming in Matlab 18
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);
myfun.m
myfun.m
function
function [f,f_prime]
[f,f_prime] == myfun(x)
myfun(x)
%% MYFUN–
MYFUN– Evaluate
Evaluate f(x)
f(x) == exp(x)-sin(x)
exp(x)-sin(x)
%% and
and its
its first
first derivative
derivative
%% [f,f_prime]
[f,f_prime] == myfun(x)
myfun(x)
f=exp(-x)-sin(x);
f=exp(-x)-sin(x);
f_prime=-exp(-x)-cos(x);
f_prime=-exp(-x)-cos(x);
Programming in Matlab 19
Function functions
Can update newton.m newtonf.m
newtonf.m
function
function [x,n]
[x,n] == newtonf(fname,x0,tol,maxit)
newtonf(fname,x0,tol,maxit)
%% NEWTON
NEWTON –– Newton’s
Newton’s method
method for for solving
solving
equations
equations
%% [x,n]
[x,n] == NEWTON(fname,x0,tol,maxit)
NEWTON(fname,x0,tol,maxit)
xx == x0;
x0; nn == 0;
0; done=0;
done=0;
while
while ~done,
~done,
nn == nn ++ 1; dx
1; f ( x, t )
dt
[f,f_prime]=feval(fname,x);
[f,f_prime]=feval(fname,x);
x_new
x_new == xx –– f/f_prime;
f/f_prime;
done=(n>maxit)
done=(n>maxit) || (( abs(x_new-x)<tol
abs(x_new-x)<tol ); );
x=x_new;
x=x_new;
end
end
>> [x,n]=newtonf(’myfun’,0,1e-3,10)
Programming in Matlab 20
Function functions in Matlab
Heavily used: integration, differentiation, optimization, …
>> help ode45
Find the solution to the ordinary differential equation
myodefun.m
myodefun.m
function
function x_dot
x_dot == myodefun(t,x)
myodefun(t,x)
%% MYODEFUN
MYODEFUN –– Define
Define RHS
RHS of
of ODE
ODE
x_dot(1,1)=x(2);
x_dot(1,1)=x(2);
x_dot(2,1)=-x(1)+0.1*(1-x(1)^2)*x(2);
x_dot(2,1)=-x(1)+0.1*(1-x(1)^2)*x(2);
>> ode45(‘myodefun’,[0 10],[1;-10]);
Programming in Matlab 21
Programming tips and tricks
Programming style has huge influence on program speed!
slow.m
slow.m
tic;
tic;
X=-250:0.1:250;
X=-250:0.1:250; fast.m
fast.m
for
for ii=1:length(x)
ii=1:length(x) tic
tic
if
if x(ii)>=0,
x(ii)>=0, x=-250:0.1:250;
x=-250:0.1:250;
s(ii)=sqrt(x(ii));
s(ii)=sqrt(x(ii)); s=sqrt(x);
s=sqrt(x);
else
else s(x<0)=0;
s(x<0)=0;
s(ii)=0;
s(ii)=0; toc;
toc;
end;
end;
end;
end;
toc
toc
Loops are slow: Replace loops by vector operations!
Memory allocation takes a lot of time: Pre-allocate memory!
Use profile to find code bottlenecks!
Programming in Matlab 22
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