Upload
alexander-jolley
View
230
Download
0
Embed Size (px)
Citation preview
8/12/2019 MATLAB Iteration
1/24
ECE 1331
MATLAB: Iteration
ECE 1331ECE 1331
MATLAB: IterationMATLAB: Iterationloops and implied loopsloops and implied loops
8/12/2019 MATLAB Iteration
2/24
8/12/2019 MATLAB Iteration
3/24
Loops and Implied Loops
loop example
8/12/2019 MATLAB Iteration
4/24
Loops and Implied Loops "iterate":
to perform again; repeat
Consider the followingproblem:
given vector of numbersnamed data
want to add up values indata greater than somescalar named val
must "iterate" throughvalues in data, comparing
each one to val, thensumming those valuesgreater than val
This is a "loop" operation, asindicated by thepseudocode:
initialize total to zero
for each value in data:if value is greater than val,add value to total
8/12/2019 MATLAB Iteration
5/24
Loops and Implied Loops
Init total to zero
Is value > val?
Add value to total
next value
For each
value in
data...
no morevalues
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
8/12/2019 MATLAB Iteration
6/24
Iteration in Spreadsheets
=SUM(B1:B8)
=IF(A8>val,A8,"")11
=IF(A7>val,A7,"")-5
=IF(A6>val,A6,"")6
=IF(A5>val,A5,"")8
=IF(A4>val,A4,"")-3
=IF(A3>val,A3,"")1
=IF(A2>val,A2,"")5
5=IF(A1>val,A1,"")3
Iteration in spreadsheets takesplace when a formula operatingon a value in a column is copieddown so that it similarly
operates on the entire columnof 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 isan implementation of the
flowchart and pseudocode.
=SUM(B1:B8)
=IF(A8>val,A8,"")11
=IF(A7>val,A7,"")-5
=IF(A6>val,A6,"")6
=IF(A5>val,A5,"")8
=IF(A4>val,A4,"")-3
=IF(A3>val,A3,"")1
=IF(A2>val,A2,"")5
5=IF(A1>val,A1,"")3
8/12/2019 MATLAB Iteration
7/24
Implied Loops in MATLAB Iteration takes place
"automatically" in MATLAB bcuzof the built-in vector operations
solution is implemented two waysso that you can see the pieces
Since data is a vector, theoperation data > val causesautomatic iteration
comparing val to each element ofdata, in turn automatic iteration also takes
place when data is given a vectorsubscript (as shown on the right)
But look carefully and see, again,that this is an implementation ofthe 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 > valbigdata = data(indices);
% sum of those values
total = sum(bigdata)
Solution in fewer steps
% sum data values > val
total = sum(data(data>val))
8/12/2019 MATLAB Iteration
8/24
8/12/2019 MATLAB Iteration
9/24
for Loops for loops in MATLAB (or any other language) are way of explicitly
implementing Loop structure for iteration
more tedious than MATLAB's implied loops, but are also more flexible
The structure of a for loop is:for loop-variable = m:s:n for loop-variable = aVector
statements statements
end end
where m:s:nare the usual expression for generating elements of a vector: m= initial value s= step or increment n= terminating value
In the second form above, aVectorcan already have a set of values
loop-variabletakes on each of the vector values for one pass through theloop, executing the statementsonce during each pass
8/12/2019 MATLAB Iteration
10/24
Examples:
Fill vector with values of cos(x)
for k = 1:101
x = (k-1)*2*pi/100;
y(k) = cos(x);
end
equivalent to:
x = linspace(0,2*pi,101);
y = cos(x);
Display the square roots of theodd integers from 1 to 9
% using explicit for loopfor n = 1:2:9
disp(sqrt(n))
end
equivalent to:
% using implied loop
n = 1:2:9;
disp(sqrt(n))
8/12/2019 MATLAB Iteration
11/24
Examples
Display the log of a set of values read
from a file
load data.txt;
for x = datalogval = log(x);
disp(['Log of ', num2str(x), ' is ', num2str(logval)])
end
8/12/2019 MATLAB Iteration
12/24
Examples Now let's do our earlier iteration example:
data = [3,4,1,-3,8,6,-5,11];val = 5;
% Loop through data
total = 0;
for n = 1:length(data)
if data(n)>val
total = total + data(n);
endend Notice that in this case we can combine the
comparison and the summing in the same pass,whereas the spreadsheet and implied loopsolutions first created a set of values bigger
than val, and then summed them up. A lessefficient for loop implementation could copythat approach
8/12/2019 MATLAB Iteration
13/24
Examples
First, create a vector of the big values
k = 0; % counter for large values
for n = 1:length(data)
if data(n)>val
k = k+1;
bigdata(k) = data(n);
endend
Now add up the big values
total = 0;
for n = 1:length(bigdata)
total = total + bigdata(n);
end
8/12/2019 MATLAB Iteration
14/24
Standard Loop Structure Programmed loop problems
can be solved with thefollowing general structure: pre-loop initialization
set up the problem, initializevariables, initialize counters,etc.
loop control: initialize,increment/modify, test
usually a loop variable isspecified, along with itsinitial value, increment valuefor each pass through theloop, and a test on thevariable for when to exit theloop)
loop body
the instructions that areexecuted each pass throughthe loop
post-loop cleanup stuff that needs to be done
when the loop is exited
allocate "space" on page for eachsection, and insert instructions intoeach section as necessary
Example: Disp. # of neg. values in data
array
data = [3,4,1,-3,8,6,-5,11];
% pre-loop initializationcounter = 0;
% loop control
for n = 1:length(data)
% loop body
if data(n)< 0
counter = counter + 1
end
end
% post-loop cleanup
disp('Number of negativevalues is: ')
disp(counter)
data = [3,4,1,-3,8,6,-5,11];
counter = 0;
for n = 1:length(data)if data(n)< 0
counter = counter + 1
endend
disp('Number of negative values is: ')disp(counter)
Well known for Loop
8/12/2019 MATLAB Iteration
15/24
Well-known for Loopexamples
Find maximum value in a vector
load data.txt;
maximum = data(1); % maximum so farfor n = 2:length(data)
if data(n)>maximum
maximum = data(n); % replace with new maximum
endend
Of course, there is also a quick function for that:
maximum = max(data);
W ll k f L
8/12/2019 MATLAB Iteration
16/24
Well-known for Loop
examplesSearch for a specific value in a vectorload data.txt;
target = input('Enter value to searchfor:');
found = 0; % Init flag to false
for n = 1:length(data)
if data(n)==target
found = 1;
break;end
end
% Display result
if(found)
disp('Value was found.')
elsedisp('Value was NOT found.')
end
Again, there is a faster way of
doing this using find():
load data.txt;
target = input('Enter value tosearch for:');
found =length(find(data==target));
% Display result
if(found)
disp('Value was found.')
else
disp('Value was NOTfound.')
end
8/12/2019 MATLAB Iteration
17/24
for Loop to Vectorize a Function
Recall that we had a problemusing an if statement with avector in a function, so welearned how to insist on ascalar argument:
function y = myabs(x);
% Test for scalar
if length(x)~=1
error('Input variablemust be scalar.')
end
% Input is scalar,proceed.
if x>=0
y = x;
else
y = -x;
end
Now we can use a for loop toprovide the iteration needed
with an if statement:function y = myabs(x);
% Assume x, and thus y, arevectors
for n = 1:length(x)if x(n)>=0
% x(n)is scalar
y(n) = x(n);
elsey(n) = -x(n);
end
end
8/12/2019 MATLAB Iteration
18/24
for Loop to Vectorize a Function
Another example: Define this function asfilteredpulse(t):
y = 0 for t= a
function y = filteredpulse(t,a);
for n = 1:length(t)
if t(n)0 & t(n)
8/12/2019 MATLAB Iteration
19/24
8/12/2019 MATLAB Iteration
20/24
while Loops for loop
number of passes through the loop is known in advance controlled by the loop index variable
while loop number of passes through the loop is not known in advance depends on a special condition that is reevaluated after each pass
Loop initialization
Is continuation
condition met?
Perform actions,
including something
that may result in
termination of loop
repeat
No
Yes
8/12/2019 MATLAB Iteration
21/24
while Loops The MATLAB while statement is:
whi l e logical-expression
statements
end
w.r.t. standard loop structure described earlier, elements of loop controlsection (initialize, increment/modify, test) are now distributed
"initialize" operation must be part of the loop initializationsection "increment/test" operation is done in the loop body while instruction itself contains on the "test" operation.
e.g. a for loop implemented with a while might look like this:
n =m
for loop-variable =m:s:n while loop-variable
8/12/2019 MATLAB Iteration
22/24
while LoopsConsider the following example:
Input the value N. Startingwith 1, compute and display allof the integer squares up toand including N. Do thiswithout taking a square root.
pseudocode:input N
initialize n to 1as long as n*n is less than
or equal to N, do thefollowing
display n*nincrement n
The MATLAB code is:
% Initialization
N = input('Enter stop
number:');n = 1;
nsq = n*n;
% Loop until N is exceeded
while nsq
8/12/2019 MATLAB Iteration
23/24
while Loops Another example:
To approximate E, sum the series expansion until the sumchanges by no more than a tolerance value entered by the user
% Initializationtol = input('Enter desired errortolerance:');
sum = 1; % first term for n=0
n = 1;
nfact = 1;
newterm = 1; % addition for n=1 (1/1!)
% Loop computing the series sum
while newterm > tol
sum = sum + newterm;n = n+1;
nfact = n*nfact; % next factorial
newterm = 1/nfact; % next term
enddisp(['E is approximately ', num2str(sum)])
8/12/2019 MATLAB Iteration
24/24