Matlab Training Session 4: Control, Flow and Functions
Course Outline Weeks: Introduction to Matlab and its Interface (Jan 13 2009) Fundamentals (Operators) Fundamentals (Flow) Importing Data Functions and M-Files Plotting (2D and 3D) Statistical Tools in Matlab Analysis and Data Structures Course Website: http://www.queensu.ca/neurosci/matlab.php
Fundamentals of Matlab 4 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 make commands easier to understand Saving M-files is far more memory efficient than saving a workspace
Week 2 Review Relational Operators < less than Relational operators are used to compare two scaler values or matrices of equal dimensions < 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’, ‘Else’, ‘Elseif’ and ‘Switch’ statements
Condition Statements If, Else, and Elseif if logical_expression 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: For loops 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); Function input output
Simple Example Find the cube of a number -> (x3) 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 >> cube(3) Ans = 125 >> cube 1.75 Ans = 5.3594 function [y] = cube(x) y = x*x*x;
Add Some Help Find the cube of a number -> (x3) 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 [y1, y2] = cube(x1, x2) % Put some text here y1 = x1*x1*x1; y2 = x2*x2*x2; >> 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 function [y1, y2] = cube(x1, x2) if nargin == 1 y1 = x1*x1*x1; y2 = nan; elseif nargin == 2 y2 = x2*x2*x2; 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 [y1, y2] = cube(x1, x2) if nargin == 1 y1 = x1*x1*x1; y2 = nan; return end y2 = x2*x2*x2; >> 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 >> cube(2) Ans = 8 >> cube([2 3]) Ans = [8 27] function [y] = cube(x) % Put some text here y = x.^3;
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 (N1…Nm) A vector of powers (P1…Pm) Outputs: A vector of raised values (N1P1 … NmPm) 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 = (N12…Nm2) 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 = x.^2; e = 0; return elseif nargin == 2 if length(x)~=length(n) y = nan; e = 1; end for i=1:length(x) y(i) = x(i)^n(i);
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 = NaN; e = 1; end for i=1:length(x) for j=1:n(i) y(i) = y(i)*x(i); e = 0;
Getting Help Help and Documentation Digital Hard Copy Accessible Help from the Matlab Start Menu Updated online help from the Matlab Mathworks website: http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html Matlab command prompt function lookup Built in Demo’s Websites Hard Copy Books, Guides, Reference The Student Edition of Matlab pub. Mathworks Inc.