Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.

Similar presentations


Presentation on theme: "Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011."— Presentation transcript:

1 Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011

2 Introduction to MATLAB - Session 3 Contents of this course Session 1 General Matrices M-files Session 2 Some matrix commands Logical expressions Graphics 1 Session 3 My functions + strings, cells Controlling program flow Session 4 Function functions Session 5 Graphics 2 More linear algebra Starting homework

3 My functions + strings and cells

4 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 calling variable space Own functions follow the same general syntax as MATLAB functions [OUTPUT parameters] = functionname(INPUT parameters); Function INPUT parameters OUTPUT parameters

5 Introduction to MATLAB - Session 3 Writing a function 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);

6 Introduction to MATLAB - Session 3 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 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 W = routine1(X,Y); Z = X+W;

7 Introduction to MATLAB - Session 3 Variating number of INPUT - variables 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

8 Introduction to MATLAB - Session 3 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 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)

9 Introduction to MATLAB - Session 3 Datatype cell array 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)

10 Introduction to MATLAB - Session 3 …back to varargin 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

11 Controlling program flow

12 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, switch Loop control  Repeat the commands this many times: for  Repeat the commands until this holds: while

13 Introduction to MATLAB - Session 3 Conditional flow control: if – elseif – else – end 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! TRUE FALSE TRUE FALSE

14 Introduction to MATLAB - Session 3 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. 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

15 Introduction to MATLAB - Session 3 Loop flow control: while 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 TRUE FALSE

16 Introduction to MATLAB - Session 3 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. 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)

17 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, 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.

18 Problems Session 3

19 Introduction to MATLAB - Session 3 Problems 1. Write function Xn = mspolygon(X,x0,a) that scales the INPUT polygon by a (a>0) and moves it by 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.  Test your function with P of Exercise 1/Session 2.

20 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.

21 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 = [1,10,100,1000,10000,100000]) and xn is a cell array with xn{j} = n(j) random points in [0,1]x[0,1] i.e. matrix of size (2,n(j)). b) Call Qpoints 1000 times to find an approximative error when computing the area of T with different n’s. Represent the results graphically.

22 >> quit …to exit MATLAB.


Download ppt "Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011."

Similar presentations


Ads by Google