Matlab Training Session 3: Control and Flow

Matlab Training Session 3:
Control and Flow

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 (2D and 3D)
7. Statistical Tools in Matlab
8. Analysis and Data Structures

Course Website:
http://www.queensu.ca/neurosci/matlab.php

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

Week 2 Review
N – Dimensional matrices
A = [1 2 4 5

6 3 8 2]

B = [5 3 7 9
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)

Week 2 Review
Scalar Operations
• Scalar (single value) calculations can be performed on matrices
and arrays
A = [1 2 4 5
6 3 8 2]

Try:
A + 10

A*5
B/2

B = [1 C = 5
7
3
3]

Week 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
6 3 8 2]

Try:

>>A + B

B = [1 C = 5
7
3
3]

>>A + C

>>A + D

D = [2 4 6 8
1 3 5 7]

Week 2 Review
Matrix Multiplication
• Built in matrix multiplication in Matlab is either:
1. Algebraic dot product
2. Element by element multiplication


Week 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

Week 2 Review
Matrix Division
• Built in matrix division in Matlab is either:
1. Left or right matrix division
2. Element by element division

Week 2 Review
Left and Right Division

• Left and Right division utilizes the / and \ operators
• Left (\) division:
X = A\B is a solution to A*X = B
• Right (/) division:
X = B/A is a solution to X*A = 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

Week 2 Review
Element by Element Division
• Element by element division of matrices is performed with the ./
operator
• Matrices must have identical dimensions

Week 2 Review
Matrix Exponents
• Built in matrix Exponentiation in Matlab is either:
1. A series of Algebraic dot products
2. Element by element exponentiation

Examples:
• A^2 = A * A
• A.^2 = A .* A

(Matrix must be square)

Week 2 Review
Relational Operators
• Relational operators are used to compare two scaler values or
matrices of equal dimensions

Relational Operators
<
less than

Greater than
>=
Greater than or equal to
==
equal

~=
not equal

Week 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!

>> 5 == 5
Ans 1
>> 20 >= 15
Ans 1

Week 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
>> find(D > 0)
• The resultant positions can be used as indexes to change these
elements
>> D(find(D>0)) = 10

D = [10 2 10 5 10 2]

Week 2 Review
The Find Function
A = [1 2 4 5
6 3 8 2]

B=7


C = [2 2 2 2
2 2 2 2]

D = [0 2 0 5 0 2]

• The ‘find’ function can also return the row and column indexes of
of matching elements by specifying row and column arguments
>> [x,y] = find(A == 5)
• The matching elements will be indexed by (x1,y1), (x2,y2), …
>> A(x,y) = 10
A = [ 1 2 4 10
6382 ]

Matrix 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
6 3 8 2]

B=2

>> D(find(D>0))
Ans 2 3 2

C = [2 2 2 2
2 2 2 2]

D = [0 2 0 3 0 2]

Matrix 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
6 3 8 2]

B=2

>> D(find(D>0))
Ans 2 3 2
>>D(D(find(D>0)))
Ans 2 0 0

C = [2 2 2 2
2 2 2 2]

D = [0 2 0 3 0 2]

Matrix 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
6 3 8 2]

B=2

>> D(find(D>0))
Ans 2 3 2
>>D(D(find(D>0)))
Ans 2 0 0
>>A(B, D(find(D>0)) )
Ans 3 8 3

C = [2 2 2 2
2 2 2 2]

D = [0 2 0 3 0 2]

B. Multiple Command
Execution

Programming 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

Programming 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

>> long_variable_name1 + long_variable_name2 + mean(long_variable_name3)

Programming 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

>> long_variable_name1 + long_variable_name2 + mean(long_variable_name3)

>> long_variable_name1 + long_variable_name2 + …
mean(long_variable_name3)

Programming Tricks
Entering Multiple Lines Without Running Them





To enter multiple lines before running any of them, use Shift+Enter
or Shift+Return.
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.

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

C. Control and Flow

Logical 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

Logical Operators
Logical Operators
&
AND
|
OR
~
NOT

A&B=?

• The & (AND) operator returns TRUE only if both A,B
values are TRUE otherwise returns FALSE
& (AND) Truth Table:

A
1
1
0
0

B
1
0
1
0

Result
1
0
0
0

Logical Operators
Logical Operators
&
AND
|
OR
~
NOT

A|B=?

• The | (OR) operator returns TRUE if either A, B is
TRUE, otherwise returns FALSE
| (OR) Truth Table:

A
1
1
0
0

B
1
0
1
0

Result
1
1
1
0

Logical Operators
Logical Operators
&
AND
|
OR
~
NOT

~A = ?
~B = ?

• The ~ (NOT) operator reverses the boolean
representation
~ (NOT) Truth Table:

A ~A
1 0
0 1

B ~B
1 0
0 1

Logical Operators
Examples:
A=0
B = false C = 1
D=8
F=[0102
0 3 0 1]
Try:
>>A & B
>>A & C
>>A & D
>>A | B
>>A | C
>>A | D
>> ~A
>> ~B
>> ~C
>> ~F
>> ~A&C
>> ~C & F

E = true

>>A & E
>>A | E
>> ~D

>>A & F
>>A | F
>> ~E

Logical Operators
Examples:
A=0
B = false
F=[0102
0 3 0 1]

C=1

D=8

E = true

>>A & B = 0
>>A & C = 0
>>A & D = 0 >>A & E = 0
>>A & F = [0 0 0 0 >>A | B = 0
>>A | C = 1
0 0 0 0] >>A | D = 1 >>A | E = 1
>>A | F = [0 1 0 1
0 1 0 1]

Logical Operators
Examples:
A=0
B = false
F=[0102
0 3 0 1]

C=1

D=8

E = true

>> ~A = 1
>> ~B = 1
>> ~C = 0
>> ~D = 0
>> ~E = 0
>> ~F =[1 0 1 0
>> ~A&C = 1 >> ~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

Logical 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
A&B|C = (A&B) | C
A|B&C = A | (B&C)

Logical 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
A&B|C = (A&B) | C
A|B&C = A | (B&C)
A&~B|C = (A&(~B)) | C
A|~B&C = A | ((~B)&C)

Control 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

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
• 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
Example
A=6

B=0

if A > 6
D = [1 2 6]
A=A+1
end
if A | B
E = mean(B)
end

Condition 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

Condition Statements
Example
A=6

if A > 6
D = [1 2 6]
A=A+1
else
D = [ 0 0 0]
A=A-1
end

B=0
if A & B
E = mean(B)
else
E=0
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

Condition Statements
Example
A=6

B=0

if A > 3
D = [1 2 6]
A=A+1
elseif A > 2
D=D+1
A=A+2
end
** Both the if and elseif statements are evaluated

Condition Statements
Switch
• The switch statement can act as many elseif statements
• Only the one case statement who’s 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

Condition 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

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
For Loops
Examples:
for i = 1:1:100
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

Loops
For Loops
• Loops can be nested in other loops
A=[]
for i = 1:m
for j = 1:n
A(i,j) = i + j
end
end
• Creates an m by n matrix A whose elements are the
sum of their matrix position

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

While Loops

Loops

Examples:
A = 6 B = 15
while A > 0 & B < 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

While Loops

Loops

Examples:
A=6
B = 15
while A > 0 & B < 10
if A < 0
A=A+1
elseif B > 10
B=B–2
end
end
• Conditional statements can be nested for specific
internal control of variables

Loops
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

Loops
Breaking out of loops
Example:
A = 6 B = 15
count = 1
while A > 0 & B < 10
A=A+1
B=B+2
count = count + 1
if count > 100
break
end
end
• Break out of the loop after 100 repetitions if the while
condition has not been met

Getting Help
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.