220 likes | 491 Vues
Introduction to MATLAB Session 3. Simopekka Vänskä, THL 2010. Session 1 General Matrices M-files Session 2 Some matrix commands Logical expressions Graphics 1. Contents of this course. Session 4 Function functions Session 5 Graphics 2 More linear algebra Starting homework.
E N D
Introductionto MATLABSession 3 Simopekka Vänskä, THL 2010
Session 1 General Matrices M-files Session 2 Some matrix commands Logical expressions Graphics 1 Contents of this course Session 4 • Function functions Session 5 • Graphics 2 • More linear algebra • Starting homework • Session 3 • My functions + strings, cells • Controlling program flow Introduction to MATLAB - Session 3
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 OUTPUT parameters Function Introduction to MATLAB - Session 3
Save the function to a m-file whose name is the function name Begin with the command function, see the example. Help consisits of the first connected comment lines. Put information! Write the command lines. Assign values for all output variables. Call the function with its name. Help by >> help ftest1 function [b,c] = ftest1(a) % function [b,c] = ftest1(a) % 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); Writing a function Introduction to MATLAB - Session 3
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 help for the visibility rules in this case. End with end –command (not obligatory if not nested) 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 statements end % function routine1 ends Z = X+W; Subfunctions Introduction to MATLAB - Session 3
Case 1: Optional variables. function z = ftest(x,p) % p optional parameter, % if p does not exist, then p = 1. if ~exist(p) p = 1; end Calling ftest: >> z = ftest(x,p) OR >> z = ftest(x) Case 2: Free parameter number. Use ”varargin” command: function z = ftest(x,varargin) vn = length(varargin); for j = 1:vn eval([’p’,num2str(j),’=varargin{j};’]) end To understand this, study first strings and cell arrays. In the same way: varargout Variating number of INPUT -variables Introduction to MATLAB - Session 3
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 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 string Introduction to MATLAB - Session 3
Element of a cell (-array) is a matrix of any datatype More precis, a cell element is a pointer to the matrix. 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 Try the following: >> s = {’name’;’age’} >> s{1} >> s(1) >> c = {rand(3),5,’name’} >> c(1) >> c{1} >> c{1:2} >> c{1}(2,3) Datatype cell array Introduction to MATLAB - Session 3
varargin is a cell array Put varargin the last input argument Call >> z=ftest(x,q1,q2,q3); vn is the number of matrices in varargin Put the input parameters to p1, p2, … 1st round string: p1 = varargin{1}; 2nd round string: p2 = varargin{2}; etc. function z = ftest(x,varargin) vn = length(varargin); for j = 1:vn eval([’p’,num2str(j),’=varargin{j};’]) end …back to varargin Introduction to MATLAB - Session 3
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
General form of if statement: if logical expression 1 statements elseif logical expression 2 statements else statements end elseif is optional There can be many elseif lines within one if-end pair else is optional Max one else line within if-end pair Use indent when writing the if statement Helps reading the code! Conditional flow control:if – elseif – else – end TRUE FALSE TRUE FALSE Introduction to MATLAB - Session 3
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. 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: for Introduction to MATLAB - Session 3
Form of the while command: while logical expression statements end Repeats the statements until the expression is false Avoid infinite loop! 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 Loop flow control: while TRUE FALSE Introduction to MATLAB - Session 3
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. 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) Break, keyboard, return, continue Introduction to MATLAB - Session 3
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, desktopprofiler • 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 • 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 • 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 • 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.