Matlab Training Session 4 Control Flow and Functions

Matlab Training Session 4: Control, Flow and Functions

Course Outline Weeks: 1. Introduction to Matlab and its Interface (Jan 13 2009) 2. Fundamentals (Operators) 3. Fundamentals (Flow) 4. Importing Data 5. Functions and M-Files 6. Plotting (2 D and 3 D) 7. Statistical Tools in Matlab 8. Analysis and Data Structures Course Website: http: //www. queensu. ca/neurosci/matlab. php

Week 4 Lecture Outline Fundamentals of Matlab 4 A. Week 3 Review B. Functions in Matlab C. Mini Project

Matlab Scripts Entering Multiple Lines Without Running Them • • • Matlab can execute sequences of commands stored in files Files that contain matlab commands have the extension ‘*. m’ *. m files are written and saved in the built in matlab m-file editor M-files are executed from the M-file editor or the command prompt M-files can call other M-files **The location path of the M-file must be set in matlab

Matlab Scripts Advantages of M-files • Easy editing and saving of work • Undo changes • Readability/Portability - non executable comments can be added using the ‘%’ symbol to make commands easier to understand • Saving M-files is far more memory efficient than saving a workspace

Week 2 Review Relational Operators • Relational operators are used to compare two scaler values or matrices of equal dimensions Relational Operators < less than <= less than or equal to > Greater than >= Greater than or equal to == equal ~= not equal

Condition Statements • It is often necessary to only perform matlab operations when certain conditions are met • Relational and Logical operators are used to define specific conditions • Simple flow control in matlab is performed with the ‘If’, ‘Elseif’ and ‘Switch’ statements

Condition Statements If, Else, and Elseif • An if statement evaluates a logical expression and evaluates a group of commands when the logical expression is true • The list of conditional commands are terminated by the end statement • If the logical expression is false, all the conditional commands are skipped • Execution of the script resumes after the end statement Basic form: if logical_expression commands end

Condition Statements If, Else, and Elseif • The elseif statement forces execution of the commands below the else statement if the original logical expression evaluates to false • Only one list of commands can be executed Basic form: if logical_expression commands 1 elseif logical_expression_2 commands 2 elseif logical_expression_3 commands 3 end

Loops • Loops are an important component of flow control that enables matlab to repeat multiple statements in specific and controllable ways • Simple repetition in matlab is controlled by two types of loops: 1. For loops 2. While loops

Loops For Loops • The for loop executes a statement or group of statements a predetermined number of times Basic Form: for index = start: increment: end statements end ** If ‘increment’ is not specified, an increment of 1 is assumed by matlab

Loops While Loops • The while loop executes a statement or group of statements repeatedly as long as the controlling expression is true Basic Form: while expression statements end

Functions • • Building blocks of programming Allow code to be generic and reusable Design from top down but build from bottom up Take a set of inputs, perform a series of manipulations and return an output

Functions in Matlab • In Matlab, each function is a. m file – It is good protocol to name your. m file the same as your function name, i. e. funcname. m • function outargs=funcname(inargs); input Function output

Simple Example • Find the cube of a number -> (x 3) • Type the code below into an. m file and save it as cube. m • Set the Matlab directory appropriately • In Matlab window, type cube(3), is the result correct? • Now you have a reusable function that can calculate the cube of any number function [y] = cube(x) y = x*x*x; >> cube(3) Ans = 125 >> cube 1. 75 Ans = 5. 3594

Add Some Help • Find the cube of a number -> (x 3) • Add commented text between the funciton declaration and the first line of code • Now type help cube in Matlab window function [y] = cube(x) % Put some text here y = x*x*x; >> help cube Put some text here

Find the cube of two numbers • Any numbers of inputs and outputs can be handled in a function • For a simple example, extend the cube function to accept two inputs and find the cube of each function [y 1, y 2] = cube(x 1, x 2) % Put some text here y 1 = x 1*x 1; y 2 = x 2*x 2; >> cube(2, 3) Ans = 8 ? ? ? >> [a b] = cube(2, 3) a=8 b = 27

nargin • Matlab will accept a function call with any number of inputs and outputs • nargin can be used to find out how many inputs the user has provided – It is automatically passed with the function [y 1, y 2] = cube(x 1, x 2) if nargin == 1 y 1 = x 1*x 1; y 2 = nan; elseif nargin == 2 y 1 = x 1*x 1; y 2 = x 2*x 2; end >> cube(2, 3) Ans = 8 >> [a b] = cube(2, 3) a=8 b = 27

return • return terminates computation of the function and returns whatever is calculated thus far function [y 1, y 2] = cube(x 1, x 2) if nargin == 1 y 1 = x 1*x 1; y 2 = nan; return end y 1 = x 1*x 1; y 2 = x 2*x 2; >> cube(2, 3) Ans = 8 >> [a b] = cube(2, 3) a=8 b = 27

Find the Cube of Any Number of Numbers • Any ideas on how to accomplish this? • Lets further extend the function to cube a vector of numbers • Before we thought of the variables as scalars, now rethink the power of vectors function [y] = cube(x) % Put some text here y = x. ^3; >> cube(2) Ans = 8 >> cube([2 3]) Ans = [8 27]

Mini-Project • Lets combine what we have learned thus far in the course – Loops, If Statements, Functions – Basic Matlab Operators • Should finish this in class today • If you get through this then you are doing well

Mini-Project • Raising any number of numbers to the nth power • Inputs: – A vector of numbers to be raised (N 1…Nm) – A vector of powers (P 1…Pm) • Outputs: – A vector of raised values (N 1 P 1 … Nm. Pm) – An error flag: 1 if error in calculation, 0 if successful • Caveats: – If only one input is provided, the function should square each entry, so output = (N 12…Nm 2) and error flag is 0 – If the length of N and P are not the same, this is an error, return anything in the output vector and a 1 in the error flag • Make sure to comment and document the function

Mini-Project • Plan before you code • Remember that xn=x*x*x*x … *x (n times) • Hint: remember the built in functions ‘length’ and ‘size’ will return the dimensions of any given variable • Ask questions and take your time
![Solution 1 (simple) function [y, e] = raise(x, n) if nargin == 1 y Solution 1 (simple) function [y, e] = raise(x, n) if nargin == 1 y](http://slidetodoc.com/presentation_image_h2/9738a8c7eb5c54d2c025f38b9ef62bcc/image-24.jpg)
Solution 1 (simple) function [y, e] = raise(x, n) if nargin == 1 y = x. ^2; e = 0; return elseif nargin == 2 if length(x)~=length(n) y = nan; e = 1; return end for i=1: length(x) y(i) = x(i)^n(i); end e = 0; return end
![Solution 2 function [y, e] = raise(x, n) y = ones(1, length(x)); if nargin Solution 2 function [y, e] = raise(x, n) y = ones(1, length(x)); if nargin](http://slidetodoc.com/presentation_image_h2/9738a8c7eb5c54d2c025f38b9ef62bcc/image-25.jpg)
Solution 2 function [y, e] = raise(x, n) y = ones(1, length(x)); if nargin == 1 [y e] = raise(x, 2*ones(1, length(x))); return elseif nargin == 2 if length(x)~=length(n) y = Na. N; e = 1; return end for i=1: length(x) for j=1: n(i) y(i) = y(i)*x(i); end e = 0; return end

Getting Help and Documentation Digital 1. Accessible Help from the Matlab Start Menu 2. Updated online help from the Matlab Mathworks website: http: //www. mathworks. com/access/helpdesk/help/techdoc/matlab. html 3. Matlab command prompt function lookup 4. Built in Demo’s 5. Websites Hard Copy 3. Books, Guides, Reference The Student Edition of Matlab pub. Mathworks Inc.
- Slides: 26