Title: Matlab Training Session 3: Control and Flow
1Matlab Training Session 3Control and Flow
2- 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
3- Week 3 Lecture Outline
- Fundamentals of Matlab 3
- A. Week 2 Review
- B. Multiple Command Execution
- Breaking up long command instructions
- Entering multiple commands for execution
- Scripts
- C. Control and Flow
- Logical Operators
- Condition Statements
- Loops
4Week 2 Review
- N Dimensional matrices
- A 1 2 4 5 B 5 3 7 9
- 6 3 8 2 1 9 9 8
- Multidimensional matrices can be created by
concatenating 2-D matrices together - The cat function concatenates matrices of
compatible dimensions together - Usage cat(dimensions, Matrix1, Matrix2)
5Week 2 Review
- Scalar Operations
- Scalar (single value) calculations can be
performed on matrices and arrays - A 1 2 4 5 B 1 C 5
- 6 3 8 2 7
- 3
- 3
- Try
- A 10
- A 5
- B / 2
6Week 2 Review
- Matrix Operations
- Matrix to matrix calculations can be performed on
matrices and arrays - Addition and Subtraction
- Matrix dimensions must be the same or the
added/subtracted value must be scalar - A 1 2 4 5 B 1 C 5 D 2 4
6 8 - 6 3 8 2 7
1 3 5 7 - 3
- 3
- Try
- gtgtA B gtgtA C gtgtA D
7Week 2 Review
- Matrix Multiplication
- Built in matrix multiplication in Matlab is
either - Algebraic dot product
- Element by element multiplication
8Week 2 Review
- The Dot Product
- A(x1,y1) B(x2,y2) C(x1,y2)
- Element by Element Multiplication
- Element by element multiplication of matrices is
performed with the . operator - Matrices must have identical dimensions
9Week 2 Review
- Matrix Division
- Built in matrix division in Matlab is either
- Left or right matrix division
- Element by element division
10Week 2 Review
- Left and Right Division
- Left and Right division utilizes the / and \
operators - Left (\) division
- X A\B is a solution to AX B
- Right (/) division
- X B/A is a solution to XA B
- Left division requires A and B have the same
number of rows - Right division requires A and B have the same
number of columns
11Week 2 Review
- Element by Element Division
- Element by element division of matrices is
performed with the ./ operator - Matrices must have identical dimensions
12Week 2 Review
- Matrix Exponents
- Built in matrix Exponentiation in Matlab is
either - A series of Algebraic dot products
- Element by element exponentiation
- Examples
- A2 A A (Matrix must be square)
- A.2 A . A
13Week 2 Review
- Relational Operators
- Relational operators are used to compare two
scaler values or matrices of equal dimensions - Relational Operators
- lt less than
- lt less than or equal to
- gt Greater than
- gt Greater than or equal to
- equal
- not equal
14Week 2 Review
- Relational Operators
- Comparison occurs between pairs of corresponding
elements - A 1 or 0 is returned for each comparison
indicating TRUE or FALSE - Matrix dimensions must be equal!
-
- gtgt 5 5
- Ans 1
- gtgt 20 gt 15
- Ans 1
15Week 2 Review
- The Find Function
- The find function is extremely helpful with
relational operators for finding all matrix
elements that fit some criteria - A 1 2 4 5 B 7 C 2 2 2 2
D 0 2 0 5 0 2 - 6 3 8 2 2
2 2 2 - The positions of all elements that fit the given
criteria are returned - gtgt find(D gt 0)
- The resultant positions can be used as indexes to
change these elements - gtgt D(find(Dgt0)) 10 D 10 2
10 5 10 2
16Week 2 Review
- The Find Function
- A 1 2 4 5 B 7 C 2 2 2 2
D 0 2 0 5 0 2 - 6 3 8 2 2
2 2 2 - The find function can also return the row and
column indexes of of matching elements by
specifying row and column arguments - gtgt x,y find(A 5)
- The matching elements will be indexed by (x1,y1),
(x2,y2), - gtgt A(x,y) 10
- A 1 2 4 10
- 6 3 8 2
-
-
17Matrix Operations
- Embedding Functions
- Functions may be embedded into other functions,
i.e. the values sent to a function can be the
result from some other function - Function embedding can be many levels deep
- Many lines of code can be condensed into one
single command - A 1 2 4 5 B 2 C 2 2 2 2
D 0 2 0 3 0 2 - 6 3 8 2 2 2 2 2
- gtgt D(find(Dgt0))
- Ans 2 3 2
18Matrix Operations
- Embedding Functions
- Functions may be embedded into other functions,
i.e. the values sent to a function can be the
result from some other function. - Function embedding can be many levels deep
- Many lines of code can be condensed into one
single command - A 1 2 4 5 B 2 C 2 2 2 2
D 0 2 0 3 0 2 - 6 3 8 2 2 2 2 2
- gtgt D(find(Dgt0))
- Ans 2 3 2
- gtgtD(D(find(Dgt0)))
- Ans 2 0 0
19Matrix Operations
- Embedding Functions
- Functions may be embedded into other functions,
i.e. the values sent to a function can be the
result from some other function. - Function embedding can be many levels deep
- Many lines of code can be condensed into one
single command - A 1 2 4 5 B 2 C 2 2 2 2
D 0 2 0 3 0 2 - 6 3 8 2 2 2 2 2
- gtgt D(find(Dgt0))
- Ans 2 3 2
- gtgtD(D(find(Dgt0)))
- Ans 2 0 0
- gtgtA(B, D(find(Dgt0)) )
- Ans 3 8 3
20B. Multiple Command Execution
21Programming Tricks
- Entering Long Lines of Code
- If a matlab command contains many calculations,
embedded functions or long variable names, it may
be necessary to split the command onto multiple
lines so that it can be read more easily - The command tells matlab to continue the
current command onto the next line
22Programming Tricks
- Entering Long Lines of Code
- If a matlab command contains many calculations,
embedded functions or long variable names, it may
be necessary to split the command onto multiple
lines so that it can be read more easily - The command tells matlab to continue the
current command onto the next line - gtgt long_variable_name1 long_variable_name2
mean(long_variable_name3)
23Programming Tricks
- Entering Long Lines of Code
- If a matlab command contains many calculations,
embedded functions or long variable names, it may
be necessary to split the command onto multiple
lines so that it can be read more easily - The command tells matlab to continue the
current command onto the next line - gtgt long_variable_name1 long_variable_name2
mean(long_variable_name3) - gtgt long_variable_name1 long_variable_name2
- mean(long_variable_name3)
24Programming Tricks
- Entering Multiple Lines Without Running Them
- To enter multiple lines before running any of
them, use ShiftEnter or ShiftReturn. - The cursor moves down to the next line, where the
next line can be written. - to run all of the lines press Enter or Return .
- This allows the list of commands to be checked
and edited before they are evaluated by matlab.
25Matlab 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
26Matlab 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
27C. Control and Flow
28Logical Operators
- Logical operators are used to compare two boolean
values - A boolean value is a logical representation of
true or false - Conventionally 1 and 0 are used to represent true
and false - In matlab when boolean comparisons are made, a
value of false or 0 represents false and any
positive integer or true represents true
29Logical Operators
- Logical Operators
- AND
- OR
- NOT
- The (AND) operator returns TRUE only if both
A,B values are TRUE otherwise returns FALSE - (AND) Truth Table A B Result
- 1
1 1 - 1
0 0 - 0
1 0 - 0
0 0
A B ?
30Logical Operators
- Logical Operators
- AND
- OR
- NOT
- The (OR) operator returns TRUE if either A, B
is TRUE, otherwise returns FALSE - (OR) Truth Table A B Result
- 1
1 1 - 1
0 1 - 0
1 1 - 0
0 0
A B ?
31Logical Operators
- Logical Operators
- AND
- OR
- NOT
- The (NOT) operator reverses the boolean
representation - (NOT) Truth Table A A B B
- 1
0 1 0 - 0
1 0 1
A ? B ?
32Logical Operators
Examples A 0 B false C 1 D
8 E true F 0 1 0 2 0 3
0 1 Try gtgtA B gtgtA C gtgtA D
gtgtA E gtgtA F gtgtA B gtgtA C
gtgtA D gtgtA E gtgtA F gtgt
A gtgt B gtgt C gtgt
D gtgt E gtgt F gtgt AC
gtgt C F
33Logical Operators
Examples A 0 B false C 1 D
8 E true F 0 1 0 2 0 3
0 1 gtgtA B 0 gtgtA C 0 gtgtA D
0 gtgtA E 0 gtgtA F 0 0 0 0 gtgtA B
0 gtgtA C 1 0 0 0
0 gtgtA D 1 gtgtA E 1 gtgtA F
0 1 0 1 0 1 0 1
34Logical Operators
Examples A 0 B false C 1 D
8 E true F 0 1 0 2 0 3
0 1 gtgt A 1 gtgt B 1 gtgt C
0 gtgt D 0 gtgt E 0 gtgt F 1 0 1 0
gtgt AC 1 gtgt C F 0 0 0 0
1 0 1 0
0 0 0 0 When performing a
boolean operation with a matrix, an element by
element boolean comparison is made
35Logical Operators
- Order of Precedence
- When performing multiple logical operations
without separating brackets, the (NOT) operator
is evaluated first, followed by the (AND)
operator and (OR) operator - ABC (AB) C
- ABC A (BC)
36Logical Operators
- Order of Precedence
- When performing multiple logical operations
without separating brackets, the (NOT) operator
is evaluated first, followed by the (AND)
operator and (OR) operator - ABC (AB) C
- ABC A (BC)
- ABC (A(B)) C
- ABC A ((B)C)
37Control and Flow
- Control flow capability enables matlab to
function beyond the level of a simple desk
calculator - With control flow statements, matlab can be used
as a complete high-level matrix language - Flow control in matlab is performed with
condition statements and loops
38Condition 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
39Condition 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
40Condition Statements
Example A 6 B 0 if A gt 6 D 1 2
6 A A 1 end if A B E
mean(B) end
41Condition Statements
- If, Else, and Elseif
- The else 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
- else
- commands 2
- end
42Condition Statements
Example A 6 B 0 if A gt 6
D 1 2 6 A A 1 else D 0
0 0 A A - 1 end
if A B E mean(B) else E 0 end
43Condition 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
44Condition Statements
Example A 6 B 0 if A gt 3
D 1 2 6 A A 1 elseif A gt 2 D
D 1 A A 2 end Both the if and
elseif statements are evaluated
45Condition Statements
- Switch
- The switch statement can act as many elseif
statements - Only the one case statement whos value satisfies
the original expression is evaluated - Basic form
- switch expression (scalar or string)
- case value 1
- commands 1
- case value 2
- commands 2
- case value n
- commands n
- end
46Condition Statements
Example A 6 B 0 switch
A case 4 D 0 0 0 A A - 1 case 5
B 1 case 6 D 1 2 6 A A
1 end Only case 6 is evaluated
47Loops
- 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
48Loops
- For Loops
- The for loop executes a statement or group of
statements a predetermined number of times - Basic Form
- for index startincrementend
- statements
- end
- If increment is not specified, an increment
of 1 is assumed by matlab
49Loops
- For Loops
- Examples
- for i 11100
- x(i) 0
- end
- Assigns 0 to the first 100 elements of vector x
- If x does not exist or has fewer than 100
elements, additional space will be automatically
allocated
50Loops
- For Loops
- Loops can be nested in other loops
- A
- for i 1m
- for j 1n
- A(i,j) i j
- end
- end
- Creates an m by n matrix A whose elements are the
sum of their matrix position
51Loops
- 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
52Loops
- While Loops
- Examples
- A 6 B 15
- while A gt 0 B lt 10
- A A 1
- B B 2
- end
- Iteratively increase A and decrease B until the
two conditions of the while loop are met - Be very careful to ensure that your while loop
will eventually reach its termination condition
to prevent an infinite loop
53Loops
- While Loops
- Examples
- A 6 B 15
- while A gt 0 B lt 10
- if A lt 0
- A A 1
- elseif B gt 10
- B B 2
- end
- end
- Conditional statements can be nested for specific
internal control of variables
54Loops
- Breaking out of loops
- The break command instantly terminates a for
and while loop - When a break is encountered by matlab, execution
of the script continues outside and after the
loop
55Loops
- Breaking out of loops
- Example
- A 6 B 15
- count 1
- while A gt 0 B lt 10
- A A 1
- B B 2
- count count 1
- if count gt 100
- break
- end
- end
- Break out of the loop after 100 repetitions if
the while condition has not been met
56Getting Help
- Help and Documentation
- Digital
- Accessible Help from the Matlab Start Menu
- Updated online help from the Matlab Mathworks
website - http//www.mathworks.com/access/helpdesk/help/tech
doc/matlab.html - Matlab command prompt function lookup
- Built in Demos
- Websites
- Hard Copy
- Books, Guides, Reference
- The Student Edition of Matlab pub. Mathworks Inc.