Presentation is loading. Please wait.

Presentation is loading. Please wait.

Matlab Training Session 4: Control, Flow and Functions

Similar presentations


Presentation on theme: "Matlab Training Session 4: Control, Flow and Functions"— Presentation transcript:

1 Matlab Training Session 4: Control, Flow and Functions

2 Course Outline Weeks: Introduction to Matlab and its Interface (Jan ) Fundamentals (Operators) Fundamentals (Flow) Importing Data Functions and M-Files Plotting (2D and 3D) Statistical Tools in Matlab Analysis and Data Structures Course Website:

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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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 = function [y] = cube(x) y = x*x*x;

16 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

17 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

18 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

19 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

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

21 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

22 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

23 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

24 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);

25 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;

26 Getting Help Help and Documentation Digital Hard Copy
Accessible Help from the Matlab Start Menu Updated online help from the Matlab Mathworks website: Matlab command prompt function lookup Built in Demo’s Websites Hard Copy Books, Guides, Reference The Student Edition of Matlab pub. Mathworks Inc.


Download ppt "Matlab Training Session 4: Control, Flow and Functions"

Similar presentations


Ads by Google