1
1
ECE 1331
MATLAB: Iteration
ECE 1331
ECE 1331
MATLAB: Iteration
loops and implied loops
loops and implied loops
2
Loops and Implied Loops
±
A loop is a structure for repeating a
A loop is a structure for repeating a
sequence of instructions
a number of times.
sequence of instructions
a number of times.
Each repetition is called a
Each repetition is called a
pass
pass
. Looping is
. Looping is
also also called iteration.
also also called iteration.
3
–T
h
i
s
i
s
a
"
loop
" operation, as
indicated by the
pseudocode
:
initialize total to zero
for each value in data:
if value is greater than val,
add value to total
Loops and Implied Loops
• "iterate":
– to perform again; repeat
• Consider the following
problem:
– given vector of numbers
named
data
– want to add up values in
data
greater than some
scalar named
val
–m
u
s
t
"
iterate
" through
values in
data
, comparing
each one to
val
, then
summing those values
greater than
val
4
Loops and Implied Loops
Init total to zero
Is value > val?
Add value to total
next value
For each
value in
data.
.
no more
values
No
Yes
Init total to zero
Look at next data
value
Is value > val?
Add value to total
More values in
data?
Yes
Yes
No
No
5
Iteration in Spreadsheets
•
Iteration in spreadsheets takes
place when a formula operating
on a value in a column is copied
down so that it similarly
operates on the entire column
of data.
•
For example:
–
the problem above is solved in
Excel as shown to the right
–
Assume that cell C1 is named
"
val
"
•
Look closely and see how this is
an implementation of the
flowchart
and
pseudocode
.
3
=IF(A1>val,A1,"")
5
=IF(A2>val,A2,"")
1
=IF(A3>val,A3,"")
-3
=IF(A4>val,A4,"")
8
=IF(A5>val,A5,"")
6
=IF(A6>val,A6,"")
-5
=IF(A7>val,A7,"")
11
=IF(A8>val,A8,"")
=SUM(B1:B8)
6
Implied Loops in MATLAB
•
Iteration takes place
"
automatically
" in MATLAB bcuz
of the built-in vector operations
•
solution is implemented two ways
so that you can see the pieces
•
Since data is a vector, the
operation
data > val
causes
automatic iteration
–c
o
m
p
a
r
i
n
g
val
to each element of
data, in turn
–
automatic iteration also takes
place when data is given a logical
subscript (as shown on the right)
•
But look carefully and see, again,
that this is an implementation of
the flowchart
data = [3,4,1,-3,8,6,-5,11];
val = 5;
Solution in several explicit steps…
% subscripts of values > val
indices = find(data>val);
% actual values > val
bigdata = data(indices);
% sum of those values
total = sum(bigdata)
Solution in fewer steps…
% sum data values > val
total = sum(data(data>val))