Introduction to MATLAB Session 3

advertisement
Introduction to MATLAB
Session 3
Simopekka Vänskä, THL
2010
Contents of this course
Session 1
 General
Session 4
 Function functions
 Matrices
 M-files
Session 5
 Graphics 2
Session 2
 Some matrix commands
 Logical expressions
 Graphics 1
Session 3
 My functions + strings, cells
 Controlling program flow
Introduction to MATLAB - Session 3
 More linear algebra
 Starting homework
My functions
+ strings and cells
Function
 Functions are m-files starting with command function
 A function creates its own variable space that includes
copies of INPUT parameters
 What the function does for the parameters in the function’s
variable space does not effect to the main variable space
 Own functions follow the same general syntax as
MATLAB functions
[OUTPUT parameters] = functionname(INPUT parameters);
INPUT
parameters
Introduction to MATLAB - Session 3
Function
OUTPUT
parameters
Writing a function
 Save the function to a m-file
function [b,c] = ftest1(a)
whose name is the function
name
 Begin with the command
function, see the example.
 Help consisits of the first
connected comment lines.
% function [b,c] = ftest1(a)
 Put information!
 Write the command lines.
 Assign values for all output
variables.
 Call the function with its name.
 Help by >> help ftest1
Introduction to MATLAB - Session 3
% Function for learning functions.
% INPUT: a matrix of doubles
% OUTPUT:
%
b a short description for
%
c the output variables is useful.
% 25.10.2010 Sp Vanska
% This is not seen as help text.
b = a+5; % this is a comment
c = sqrt(a);
Subfunctions
Some routines are practical to put
to subfunctions
 No need for a separate m-file
 Start with function –command
 You can also write
subfunctions in subfunctions.
 See ”nested functions” of
function Z = ftest1(X)
% this is the main function
% with m-file ftest1.m
Y = X+2;
function W = routine1(X,Y)
% this is a subfunction
help for the visibility rules in
this case.
statements
 End with end –command (not
obligatory if not nested)
end % function routine1 ends
Z = X+W;
Introduction to MATLAB - Session 3
Variating number of INPUT variables
Case 1: Optional variables.
Case 2: Free parameter number.
function z = ftest(x,p)
% p optional parameter,
% if p does not exist, then p = 1.
Use ”varargin” command:
if ~exist(p)
p = 1;
end
vn = length(varargin);
Calling ftest:
>> z = ftest(x,p)
OR
>> z = ftest(x)
end
Introduction to MATLAB - Session 3
function z = ftest(x,varargin)
for j = 1:vn
eval([’p’,num2str(j),’=varargin{j};’])
 To understand this, study first
strings and cell arrays.
 In the same way: varargout
Datatype string
 String matrix is an array of
chars.
 String can be created by
>> s = ’abcd’;
 String array has to be
rectangular (examples right).
 Related commands:
 num2str, str2num: convert
numbers to strings, and vice
versa
 eval: executes the string
Introduction to MATLAB - Session 3
Try the following:
>> s = [’name’;’age’]
>> s = [’name’;’age1’]
>> a = ’12’;
>> b = 2;
>> a+b
>> s1 = [a,’ + ’,num2str(b)]
>> s2 = str2num(a) + b
>> eval(s1)
Datatype cell array
Try the following:
 Element of a cell (-array) is a
matrix of any datatype
 More precis, a cell element is
a pointer to the matrix.
>> s = {’name’;’age’}
>> s{1}
>> s(1)
 Create a cell by listing the
elements in curly braces, {}.
 Refer to the j’th element matrix:
cellname{j}
 Remark: cellname(j) is just
the pointer to the matrix j
 cell(n,m) : creates (n,m) cell
array of empty matrices
Introduction to MATLAB - Session 3
>> c = {rand(3),5,’name’}
>> c(1)
>> c{1}
>> c{1:2}
>> c{1}(2,3)
…back to varargin
function z = ftest(x,varargin)
 varargin is a cell array
 Put varargin the last input
argument
 Call >> z=ftest(x,q1,q2,q3);
vn = length(varargin);
 vn is the number of matrices in
varargin
for j = 1:vn
eval([’p’,num2str(j),’=varargin{j};’])
end
 Put the input parameters to p1,
p2, …
 1st round string: p1 = varargin{1};
 2nd round string: p2 = varargin{2};
 etc.
Introduction to MATLAB - Session 3
Controlling program flow
Program flow control
Controlling what statements (commands) will be executed
next
 Conditional control
 In case A do this, but in case B do that : if
 Loop control
 Repeat the commands this many times: for
 Repeat the commands until this holds: while
Introduction to MATLAB - Session 3
Conditional flow control:
if – elseif – else – end
General form of if statement:
 elseif is optional
 There can be many elseif
if logical expression 1
lines within one if-end pair
TRUE
FALSE
statements
 Max one else line within if-
elseif logical expression 2
TRUE
FALSE
 else is optional
statements
end pair
 Use indent when writing the if
statement
else
statements
end
Introduction to MATLAB - Session 3
 Helps reading the code!
Loop flow control: for
A simple form of for command:
for k = 1:n
statements
end
 Repeats the statements n times
 1st round, k has value 1
 2nd round, k has value 2
 etc.
A simple generalization of for:
for k = v
% v vector
statements
end
 Repeats length(v) times
 1st round, k has value v(1)
 2nd round, k has value v(2)
 etc.
Introduction to MATLAB - Session 3
General form of for:
for k = expression
statements
end
 Here, k runs through the
columns of the expression.
Try:
>> for k = 1:n
k
end
>> for k = rand(3)
k
end
Loop flow control: while
Form of the while command:
while logical expression
TRUE
FALSE
statements
end
 Repeats the statements until the
expression is false
 Avoid infinite loop!
Introduction to MATLAB - Session 3
 Tip: If the logical expression is
complicated, or has many
conditions, it is often easier to
use extra logical variable:
dothis = 1;
loopno = 1;
while dothis
statements
loopno = loopno+1;
if (some given stop condition)
dothis=0;
elseif loopno>1000
dothis=0;
end
end
Break, keyboard, return, continue
BREAK terminates the loop (for or
while) and program continues
from end-command
 In multiple loop case, only the
innermost loop is terminated
CONTINUE terminates this iteration
of the loop and continues from
the next iteration step
KEYBOARD stops executing the file
and gives control to user at that
point.
 Useful especially when
debugging the code.
Introduction to MATLAB - Session 3
for j=1:n
…
if something
break
end
…
end
statement % here if break
RETURN
 Returns the program flow to
the invoking m-file
 Returns the flow to the m-file
from the keyboard mode
(type return + enter)
Some practical tips
 Long lines: [1 2 3 4 ...
5 6 7 8];
 To make the code more readable
 Use indents
 Write comments
 Try to use matrices (instead of for-loops e.g.)
 Use profiling to speed up your programs,
desktopprofiler
 Some times only one routine takes most of the time  improve
it!
 Do not repeat the same computations
 Try to minimize the arguments of the functions, e.g. only x
instead of x*ones(1,1000).
 Keep always in your mind the memory usage.
Introduction to MATLAB - Session 3
Problems
Session 3
Problems
1. Write function Xn = mspolygon(X,x0,a) that scales the
INPUT polygon by a (a>0) and moves its center to point
x0, and draws both polygons in one image.
 The polygon is given by matrix X whose columns are the
nodes (corner points) of the polygon. The output Xn is the
nodes of new polygon.
 Define the centerpoint to be the average of the nodes.
 Test your function with P of Exercise 1/Session 2.
Introduction to MATLAB - Session 3
Problems
2. Write a function Xt = roundt(X,t) that rounds real
numbers to grid tZ = (…,-2t,-t,0,t,2t,…) and complex
numbers to grid tC = tZ+itZ.
 The input X can be a matrix and t>0.
 Test your function (real case) with X = -5:.01:5 and
t=sqrt(2)/2. Draw a picture.
 Test your function (complex case) with X =
randn(1,5)+2*i*randn(1,5) and t=0.5. Draw a picture.
Write both test cases in one m-file.
Introduction to MATLAB - Session 3
Problems
3. Continue the Triangle Exercise 7/Session 2.
a) Write a function xn = Qpoints(n) where the input
argument n is a vector
n(j) = number of random points in [0,1]x[0,1]
(e.g. n = 1000:1000:10000)
and xn is a cell array with
xn{j} = n(j) random points.
b) Call Qpoints many times to find an approximative
error when computing the area of T with different n’s.
Represent the results graphically.
Introduction to MATLAB - Session 3
>> quit
…to exit MATLAB.
Download