Section 5 Structured Programming in MATLAB
Section 5 Structured Programming in MATLAB
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
In MATLAB:
if condition
statements1
else
statements2
end
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:
switch testexpression
case value1
statements1
case value2
statements2
otherwise
statements3
end
switch A
case 1
B = 2;
case 2
B = 8;
case 3
B = -5;
otherwise
B = 84;
end
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
while (1)
statements repeat infinitely
end
Useful for
multiple break
conditions
Control over
break point
Could also
modify the
while condition
A surface in three-
dimensional space
In Section 7, we’ll learn how
to generate such a plot
−𝑥𝑥 2 −𝑦𝑦 2
𝑧𝑧 = 𝑥𝑥 ⋅ 𝑒𝑒
Evaluate the function over a range of 𝑥𝑥 and 𝑦𝑦
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
Note the red line to the right of line 14 and the red squiggle
under x in the following for loop:
Preallocation speeds up
the loop up significantly
But …
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 …