SECTION 5:
STRUCTURED
PROGRAMMING IN MATLAB
ENGR 112 – Introduction to Engineering Computing
2 Conditional Statements
• if statements
• if…else statements
• Logical and relational operators
• switch…case statements
K. Webb ENGR 112
The if Statement
3
We’ve already seen the if structure
If X is true, do Y, if not, don’t do Y
In either case, then proceed to do Z
In MATLAB:
if condition
statements
end
Statements are executed if condition is true
Condition is a logical expression
Either true (evaluates to 1) or false (evaluates to 0)
Makes use of logical and relational operators
May use a single line for a single statement:
if condition, statement, end
K. Webb ENGR 112
Logical and Relational Operators
4
Operator Relationship or Logical Operation Example
== Equal to x == b
~= Not equal to k ~= 0
< Less than t < 12
> Greater than a > -5
<= Less than or equal to 7 <= f
>= Greater than or equal to (4+r/6) >= 2
NOT– negates the logical value of an
~ expression
~(b < 4*g)
AND – both expressions must
& or && evaluate to true for result to be true
(t > 0)&&(c == 5)
OR – either expression must
| or || evaluate to true for result to be true
(p > 1)||(m > 3)
K. Webb ENGR 112
Short-Circuit Logical Operators
5
Note that there are two AND and two OR operators
available in MATLAB
AND: & or &&
OR: | or ||
Can always use the single operators: & and |
The double operators are short-circuit operators
Only evaluate the second expression if necessary –
faster
Can only be used with scalar expressions
K. Webb ENGR 112
The if…else Structure
6
The if … else structure
Perform one process if a condition
is true
Perform another if it is false
In MATLAB:
if condition
statements1
else
statements2
end
K. Webb ENGR 112
The if…elseif…else Structure
7
The if … elseif … else structure
If a condition evaluates as false, check another condition
May have an arbitrary number of elseif statements
In MATLAB:
if condition1
statements1
elseif condition2
statements2
else
statements3
end
K. Webb ENGR 112
The if…else, if…elseif…else Structures
8
Some examples:
Note that && and || are used here, because
expressions involve scalars
The single logical operators, & and |, would work just
as well
K. Webb ENGR 112
The if…elseif Structure
9
We can have an if statement
without an else
Similarly, an if…elseif
structure need not have an
else
In MATLAB:
if condition1
statements1
elseif condition2
statements2
end
K. Webb ENGR 112
The switch Structure
10
The switch structure evaluates a single test expression
Branching determined by the value of the test expression
switch testexpression
case value1
statements1
case value2
statements2
otherwise
statements3
end
An alternative to an if…elseif…else structure
K. Webb ENGR 112
The switch Structure
11
An example – set the value of variable B to different
values depending on the value of variable A:
otherwise serves the same purpose as else
If the test expression does not equal any of the specified
cases, execute the commands in the otherwise block
K. Webb ENGR 112
The switch Structure
12
In flowchart form, there is no direct translation for the switch
structure
We’d represent it using an if…elseif…else structure
But, if there were, it might look something like this:
switch A
case 1
B = 2;
case 2
B = 8;
case 3
B = -5;
otherwise
B = 84;
end
K. Webb ENGR 112
The switch Structure
13
An alternative to an if…elseif…else structure
Result is the same
Code may be more readable
K. Webb ENGR 112
14 while Loops
K. Webb ENGR 112
The while loop
15
The while loop
While X is true, do A
Once X becomes false, proceed to B
In MATLAB:
while condition
statements
end
Statements are executed as long
as condition remains true
Condition is a logical expression
K. Webb ENGR 112
while Loop – Example 1
16
Consider the following while loop example
Repeatedly increment x by 7 as long as x is less than or equal to 30
Value of x is displayed on each iteration, due to lack of output-
suppressing semicolon
x values displayed: 19, 26, 33
x gets incremented beyond 30
All loop code is executed as long as the condition was true at the
start of the loop
K. Webb ENGR 112
The break Statement
17
Let’s say we don’t want x to increment beyond 30
Add a conditional break statement to the loop
break statement causes loop exit before executing all code
Now, if (x+7)>30, the program will break out of the loop and
continue with the next line of code
x values displayed: 19, 26
For nested loops, a break statement breaks out of the current
loop level only
K. Webb ENGR 112
while Loop – Example 1
18
The previous example could be simplified by modifying the
while condition, and not using a break at all
Now the result is the same as with the break statement
x values displayed: 19, 26
This is not always the case
The break statement can be very useful
May want to break based on a condition other than the loop condition
break works with both while and for loops
K. Webb ENGR 112
while Loop – Example 2
19
Next, let’s revisit the while loop
examples from Section 4
Use input.m to prompt for input
Use display.m to return the result
K. Webb ENGR 112
while Loop – Example 3
20
Here, we use a while loop to
calculate the factorial value of a
specified number
K. Webb ENGR 112
while Loop – Example 3
21
Add error checking to ensure that x
is an integer
One way to check if x is an integer:
K. Webb ENGR 112
while Loop – Example 3
22
Another possible method for
checking if x is an integer:
K. Webb ENGR 112
Infinite Loops
23
A loop that never terminates is an infinite loop
Often, this unintentional
Coding error
Other times infinite loops are intentional
E.g., microcontroller in a control system
A while loop will never terminate if the while condition
is always true
By definition, 1 is always true:
while (1)
statements repeat infinitely
end
K. Webb ENGR 112
while (1)
24
The while (1) syntax can be used in conjunction with a
break statement, e.g.:
Useful for
multiple break
conditions
Control over
break point
Could also
modify the
while condition
K. Webb ENGR 112
25 for Loops
K. Webb ENGR 112
The for Loop
26
The for loop
Loop instructions execute a specified
number of times
In MATLAB:
for index = start:step:stop
statements
end
Note the syntax – looks like a vector
definition
Statements are executed once for each
element in the vector
However, index is actually a scalar
Increments through the vector of values
K. Webb ENGR 112
for Loop – Example 1
27
Next, we’ll revisit the for loop
examples from Section 4
Loop iterates 5 times
Value of scalar variable, x, reassigned
on each iteration
K. Webb ENGR 112
for Loop – Example 2
28
Here, x is defined as a vector
Loop still iterates 5 times
Successive values appended to the
end of x
x grows with each iteration
K. Webb ENGR 112
for Loop – Example 3
29
In this case the loop counter is not
used at all within the loop
Random number generated on each
of 10 iterations
K. Webb ENGR 112
30 Nested Loops
K. Webb ENGR 112
Nested Loop – Example 1
31
Recall the nested for loop example
from Section 4
Generate a matrix 𝐶𝐶 whose entries
are the squares of the elements in 𝐵𝐵
Nested for loop
Outer loop steps through rows
Counter is row index
Inner loop steps through columns
Counter is column index
K. Webb ENGR 112
Nested Loop – Example 1
32
K. Webb ENGR 112
Nested for Loop – Example 2
33
Evaluate a function of two variables:
−𝑥𝑥 2 −𝑦𝑦 2
𝑧𝑧 = 𝑥𝑥 ⋅ 𝑒𝑒
over a range of −2 ≤ 𝑥𝑥 ≤ 2 and −2 ≤ 𝑦𝑦 ≤ 2
A surface in three-
dimensional space
In Section 7, we’ll learn how
to generate such a plot
K. Webb ENGR 112
Nested for Loop – Example 2
34
−𝑥𝑥 2 −𝑦𝑦 2
𝑧𝑧 = 𝑥𝑥 ⋅ 𝑒𝑒
Evaluate the function over a range of 𝑥𝑥 and 𝑦𝑦
First, define x and y
vectors
Use a nested for
loop to step through
all points in this
range of the x-y
plane
K. Webb ENGR 112
35 The MATLAB Debugger
K. Webb ENGR 112
Debugging
36
You’ve probably already realized that it’s not uncommon for your
code to have errors
Computer code errors referred to as bugs
Three main categories of errors
Syntax errors prevent your code from running and generate a MATLAB
error message
Runtime errors – not syntactically incorrect, but generate an error upon
execution – e.g., indexing beyond matrix dimensions
Algorithmic errors don’t prevent your code from executing, but do
produce an unintended result
Syntax and runtime errors are usually more easily fixed than
algorithmic errors
Debugging – the process of identifying and fixing errors is an
important skill to develop
MATLAB has a built-in debugger to facilitate this process
K. Webb ENGR 112
Debugging
37
Identifying and fixing errors is difficult because:
Programs run seemingly instantaneously
Incorrect output results, but can’t see the intermediate
steps that produced that output
Basic debugging principles:
Slow code execution down – allow for stepping through
line-by-line
Provide visibility into the code execution – allow for
monitoring of intermediate steps and variable values
K. Webb ENGR 112
MATLAB Debugger – Breakpoints
38
Breakpoint – specification of a line of code at which
MATLAB should pause execution
Set by clicking on the dash to the left of a line of code in
an m-file
MATLAB will execute the m-file up to this line, then pause
Clicking here sets a
breakpoint
Indicated by red
circle
K. Webb ENGR 112
MATLAB Debugger – Breakpoints
39
Click Run to begin execution
Execution halts at the
breakpoint
Before executing that line
Command window prompt
changes to K>>
Can now interactively enter
commands
Toolbar buttons change
from RUN to DEBUG
K. Webb ENGR 112
MATLAB Debugger – Breakpoints
40
Click Step to execute the
current line of code
Green arrow indicator
advances to the next line
Variable, m, defined on
previous line (line 16) is
now available in the
workspace
Can be displayed in the
command window
K. Webb ENGR 112
Debugger – Example
41
Recall a previous example of an algorithm to square every
element in a matrix
Let’s say we run our m-file and get the following result:
Resulting matrix is transposed
Use the debugger to figure out why
K. Webb ENGR 112
Debugger – Example
42
Set a breakpoint in the
innermost for loop
Click Run, code executes
through the first iteration
of the inner for loop
Workspace shows i=1
and j=1
Display B(i,j) and
C(i,j) in the command
window
Both are as expected
K. Webb ENGR 112
Debugger – Example
43
Click Continue, code
executes until it hits the
breakpoint again
One more iteration of
inner for loop
Now, i=1 and j=2
First row, second column
B(i,j) = 2, as
expected
But, C(i,j) = 81
Should be 4
K. Webb ENGR 112
Debugger – Example
44
We see that C(1,2) is being set to B(2,1)^2
This leads us to an error on line 21 of the code
K. Webb ENGR 112
45 Miscellany
K. Webb ENGR 112
Sections
46
Define sections within an m-file
Execute isolated blocks of code
Starts with a double comment
Ends at the start of the next
section
Useful for debugging, particularly
if running the entire m-file is
time-consuming
To run a section:
Place cursor in section and type
Ctrl+Enter
Click the Run Section button
K. Webb ENGR 112
Preallocation
47
Note the red line to the right of line 14 and the red squiggle
under x in the following for loop:
Mouse over the line or the squiggle to see the following
warning:
The size of x grows with each iteration of the loop
Inefficient - slow
K. Webb ENGR 112
Preallocation
48
When you assign a variable, MATLAB must store it
in memory
Amount of memory allocated for storage depends on
the size of the array
If the variable grows it must be copied to a new, larger
block of available memory – slow
If the ultimate size of a variable is known ahead of
time, we can preallocate memory for it
Assign a full-sized array of all zeros
Overwrite elements on each iteration
Array size remains constant
K. Webb ENGR 112
Preallocation – Example
49
A nested for loop stepping
through an 𝑁𝑁 × 𝑁𝑁 matrix
Here N = 100
Time the loop with and
without preallocation
Use tic … toc
Preallocation speeds up
the loop up significantly
But …
K. Webb ENGR 112
Preallocation – Example
50
An accurate comparison
must account for the cost
of preallocation
Start the timer before
preallocating
Still significantly faster,
even accounting for
preallocation
Note that times vary from
run to run
But …
K. Webb ENGR 112
Preallocation – Example
51
6 msec vs. 9 msec? So what?
Difference is imperceptible
Now, increase N to 5e3
25e6 elements in A!
A significant, and very
noticeable, difference
Preallocation is always a
good practice
K. Webb ENGR 112