1 ECE 1331 MATLAB: Iteration loops and implied loops.

40
1 ECE 1331 ECE 1331 MATLAB: Iteration MATLAB: Iteration loops and implied loops loops and implied loops

Transcript of 1 ECE 1331 MATLAB: Iteration loops and implied loops.

Page 1: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

1

ECE 1331ECE 1331

MATLAB: IterationMATLAB: Iteration

ECE 1331ECE 1331

MATLAB: IterationMATLAB: Iterationloops and implied loopsloops and implied loops

Page 2: 1 ECE 1331 MATLAB: Iteration 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 passpass. Looping is . Looping is also also called iteration.also also called iteration.

Page 3: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

3

– This is 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

– must "iterate" through values in data, comparing each one to val, then summing those values greater than val

Page 4: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

4

Loops and Implied Loops

Init total to zero

Is value > val?

Add value to total

next value

For eachvalue indata...

no morevalues

No

Yes

Init total to zero

Look at next datavalue

Is value > val?

Add value to total

More values indata?

Yes

Yes

No

No

Page 5: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

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)  

Page 6: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

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

– comparing 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 > valindices = find(data>val); % actual values > valbigdata = data(indices); % sum of those valuestotal = sum(bigdata)

Solution in fewer steps…

% sum data values > valtotal = sum(data(data>val))

Page 7: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

7

Page 8: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

8

“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 statementsend end

• where m:s:n are the usual expression for generating elements of a vector:

– m = initial value– s = step or increment– n = terminating value

• In the second form above, aVector can already have a set of values

• loop-variable takes on each of the vector values for one pass through the loop, executing the statements once during each pass

Page 9: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

9

Examples:

Display the square roots of the odd integers from 1 to 9

% using explicit for loopfor n = 1:2:9

disp(sqrt(n))end

• equivalent to:

% using implied loopn = 1:2:9; disp(sqrt(n))

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);

Page 10: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

10

Examples

Display the log of a set of values read from a file

load data.txt;

for x = data

logval = log(x);

disp(['Log of ', num2str(x), ' is ', num2str(logval)])

end

Page 11: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

11

Examples• Now let's do our earlier iteration example:

data = [3,4,1,-3,8,6,-5,11];val = 5;% Loop through datatotal = 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 loop solutions first created a set of values bigger than val, and then summed them up. A less efficient “for” loop implementation could copy that approach…

Page 12: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

12

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

Page 13: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

13

Standard Loop Structure

• Programmed loop problems can be solved with the following general structure:– pre-loop initialization

• set up the problem, initialize variables, initialize counters, etc.

– loop control: initialize, increment/modify, test

• usually a loop variable is specified, along with its initial value, increment value for each pass through the loop, and a test on the variable for when to exit the loop)

– loop body• the instructions that are

executed each pass through the loop

– post-loop cleanup• stuff that needs to be done

when the loop is exited

• allocate "space" on page for each section, and insert instructions into each section as necessary

• Example:

– Disp. # of neg. values in data array

data = [3,4,1,-3,8,6,-5,11];% pre-loop initialization

counter = 0;% loop controlfor n = 1:length(data)% loop body

if data(n)< 0counter = counter + 1

endend% post-loop cleanupdisp('Number of negative values

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 + 1end

end

disp('Number of negative values is: ')disp(counter)

Page 14: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

14

Well-known “for” Loop examples

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);

Page 15: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

15

Well-known “for” Loop examples

Search for a specific value in a vector

load data.txt;target = input('Enter value to search

for:');found = 0; % Init flag to falsefor n = 1:length(data) if data(n)==target found = 1; break; endend% Display resultif(found) disp('Value was found.')else disp('Value was NOT found.')end

• Again, there is a faster way of doing this using find():

load data.txt;target = input('Enter value to

search for:');found =

length(find(data==target));% Display resultif(found) disp('Value was found.')else disp('Value was NOT

found.')end

Page 16: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

16

for Loop to Vectorize a Function• Recall that we had a

problem using an if statement with a vector in a function, so we learned how to insist on a scalar argument:

function y = myabs(x);% Test for scalarif length(x)~=1

error('Input variable must be scalar.')

end% Input is scalar,

proceed.if x>=0

y = x;else

y = -x;end

• Now we can use a for loop to provide the iteration needed with an if statement:

function y = myabs(x);% Assume x, and thus y, are

vectorsfor n = 1:length(x)

if x(n)>=0 % x(n)is scalar

y(n) = x(n);else

y(n) = -x(n);end

end

Page 17: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

17

for Loop to Vectorize a Function

• Another example: Define this function as filteredpulse(t):

• y = 0 for t<=0• y = 1 – exp(-t) for 0 < t <

a• y = (1-exp(-a)exp(a-t) for t >= a

function y = filteredpulse(t,a);for n = 1:length(t) if t(n)<=0 y(n) = 0; elseif t(n)>0 & t(n)<a y(n) = 1-exp(-t(n)); else y(n) = (1-exp(-a))*exp(a-t(n)); endend

-5 0 5 100

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

Page 18: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

18

Operational Issues with a FOR

• What is value of loop index when loop is complete?– Next Value or Last Value?

for n=1:5 disp(n) end disp(n)%Last value

Page 19: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

19

Operational Issues with a FOR

• What happens if control vector is "empty"?– Body skipped or execute once?

for n=1:-5 disp(n) end disp(n)%n = []

Page 20: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

20

Operational Issues with a FOR• What happens if loop

index is changed inside body?

for n=1:5 disp(n) n=n+2; disp(n) end disp(n)

• 1• 3• 2• 4• 3• 5• 4• 6• 5• 7• 7

Page 21: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

21

General Rule for for Loop• Do NOT explicitly change the

control variable inside the loop!

Page 22: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

22

How do we get out of a loop?• break;

– Causes an immediate exit of a loop– Example: total=0; for n=1:1000 total=total+n^2; if(total>400) break; end end disp(['Smallest integer = ',num2str(n)])

Page 23: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

23

Skipping Part of a loop• continue;

– This statement causes remaining statements in body of loop to be skipped.

– Control passes to next execution of loop total=0; for n=1:1000 if(mod(n,3)==0) continue; end total=total+n; end

Page 24: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

24

Operational Issues with a for loop

• Can loop control be a matrix rather than a vector?

642

531A

for n=Asize(n)disp(n)end

ans =2 1n = 1 2ans =2 1n = 3 4ans =2 1n = 5 6

Page 25: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

25

Standard Loop Problems• Counting the number

of occurrences• Summing

expressions• Multiplying

expressions• Finding extreme

values• "Vectorizing" a

function

• Finding a target• Early exit/use of a

flag• Creating a new array

of the same size• Creating a new array

of a different size• Interchanging values

in an array

Page 26: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

26

Nested Loops• When a loop is contained in the

body of another loop, we refer to them as nested loops.

• All parts of the basic structure of a loop are still seen in each loop

Page 27: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

27

Nested Loops• pre-outer loop initialization• outer loop control• outer loop body• pre-inner loop initialization•   inner loop control•   inner loop body•   inner loop cleanup• outer loop body resumes•  outer loop cleanup

Page 28: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

28

Nested Loops & Matrices• Whereas single loop problems

frequently involve vectors, nested loops are usually required when processing matrices.

• The outer loop iterates over the rows, while the inner loop iterates over the elements in each row (columns)

Page 29: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

29

Nested Loops & Matrices• Or the outer loop iterates over the

columns while the inner loop iterates over the elements in each column (rows)

• Solve from the "inside out"—figure out what the innermost loop must do with each row (column) and then enclose it in a loop over all the rows (columns)

Page 30: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

30

Example: Given array A, how many rows sum to more than 100?

• Solution: inner loop: sum the values in a row

• Outer loop: count the number of times the sum exceeds 100.

Page 31: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

31

[nrows ncols] = size(A);count = 0;for m=1:nrows % for each row

total = 0;for n=1:ncols % each col in the row

total = total + A(m,n);endif total >100

count = count + 1;end

enddisp('Number of times:')disp(count)

Page 32: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

32

Example: Given an array data,

append to each column the average of the values in that column

• Solution: Inner loop: compute average value

of the columnOuter loop: do so for each column &

append

Page 33: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

33

[nrows ncols] = size(data);for n=1:ncols % for each column…

total = 0;for m=1:nrows % go down the column

total = total + data(m,n);endaverage = total /nrows; % average of that columndata(nrows+1,n) = average

end

Page 34: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

34

Example: Given a file containing the temperature at noon each day for several weeks,in how many weeks was the maximum temperature for the week at least 5 degrees higher than the average temperature for the week?

Page 35: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

35

Solution: We want to count something, so initialize counter. Then for each week, determine both the average temperature and the high temperature for that week. Compare to see if we should increment the count.

Page 36: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

36

clc, clear%load temp; days in cols, weeks in rowstemps = load('temperatures.txt'); [nrows ncols] = size(temps);count = 0; %initial counterfor m = 1:nrows %outer loop for weeks

total = 0; %initial accumulator for summaxval = -500; %initial candidate for week max% Inner loop - compute avg and maxfor n = 1:ncols

total = total + temps(m,n);if temps(m,n) > maxval

maxval = temps(m,n);end %endif

end %end inner loop

Page 37: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

37

disp(['For week',num2str(m),'max is',num2str(maxval)])average = total/ncols; %weekly average

disp(['& average is ',num2str(average)])% Now test for countif maxval >= average + 5

count = count + 1;end %endif

end %end outer loop% Display resultdisp('Number of weeks is:')disp(count)

Page 38: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

38

Example: Given a file of noon temperatures, find the first week having at least three days of temperatures over 80 degrees.

Solution: Search through weeks using a flag. For each week, count the number of days greater than 80.

Page 39: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

39

clear,clctemps = load('temperatures.txt'); %load the data[nweeks ndays] = size(temps);%initial flag for foundthreeFound = 0;for week = 1:nweeks %outer loop on weeks

count = 0; %initial counter for hot days% Inner loop - count days over 80for day = 1:ndays

if temps(week,day) > 80count = count + 1; %increment count

end %endif end %end day loop

Page 40: 1 ECE 1331 MATLAB: Iteration loops and implied loops.

40

% Check count, exit if doneif count >= 3

threeFound = 1; %set flagweekNumber = week; % save the week indexbreak; %break out of week loop

end %endifend

if threeFounddisp('1st week over 80 three times is:')disp(weekNumber)

elsedisp('There were no weeks over 80 three times.')

end