Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 ECE 1331 MATLAB: Iteration loops and implied loops.

Similar presentations


Presentation on theme: "1 ECE 1331 MATLAB: Iteration loops and implied loops."— Presentation transcript:

1 1 ECE 1331 MATLAB: Iteration loops and implied loops

2 2 Loops and Implied Loops A loop is a structure for repeating a sequence of instructions a number of times. Each repetition is called a pass. Looping is also also called iteration. A loop is a structure for repeating a sequence of instructions a number of times. Each repetition is called a pass. Looping is also also called iteration.

3 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

4 4 Loops and Implied Loops

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

7 7

8 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:nfor loop-variable = aVector statements statements 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

9 9 Examples: Display the square roots of the odd integers from 1 to 9 % using explicit for loop for n = 1:2:9 disp(sqrt(n)) end equivalent to: % using implied loop n = 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);

10 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

11 11 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); end 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…

12 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); end Now add up the big values total = 0; for n = 1:length(bigdata) total = total + bigdata(n); end

13 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 control for n = 1:length(data) % loop body if data(n)< 0 counter = counter + 1 end % post-loop cleanup disp('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 + 1 end disp('Number of negative values is: ') disp(counter)

14 14 Well-known “for” Loop examples Find maximum value in a vector load data.txt; maximum = data(1); % maximum so far for n = 2:length(data) if data(n)>maximum maximum = data(n); % replace with new maximum end Of course, there is also a quick function for that: maximum = max(data);

15 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 false for n = 1:length(data) if data(n)==target found = 1; break; end % Display result if(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 result if(found) disp('Value was found.') else disp('Value was NOT found.') end

16 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 scalar if 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 vectors for n = 1:length(x) if x(n)>=0 % x(n)is scalar y(n) = x(n); else y(n) = -x(n); end

17 17 for Loop to Vectorize a Function Another example: Define this function as filteredpulse(t): y = 0for 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)); end

18 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

19 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 = []

20 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

21 21 General Rule for for Loop Do NOT explicitly change the control variable inside the loop!

22 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 disp(['Smallest integer = ',num2str(n)])

23 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

24 24 Operational Issues with a for loop Can loop control be a matrix rather than a vector? for n=A size(n) disp(n) end ans = 2 1 n = 1 2 ans = 2 1 n = 3 4 ans = 2 1 n = 5 6

25 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

26 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

27 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

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

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

30 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.

31 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); end if total >100 count = count + 1; end disp('Number of times:') disp(count)

32 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 column Outer loop: do so for each column & append

33 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); end average = total /nrows; % average of that column data(nrows+1,n) = average end

34 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?

35 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.

36 36 clc, clear %load temp; days in cols, weeks in rows temps = load('temperatures.txt'); [nrows ncols] = size(temps); count = 0; %initial counter for m = 1:nrows %outer loop for weeks total = 0; %initial accumulator for sum maxval = -500; %initial candidate for week max % Inner loop - compute avg and max for n = 1:ncols total = total + temps(m,n); if temps(m,n) > maxval maxval = temps(m,n); end %endif end %end inner loop

37 37 disp(['For week',num2str(m),'max is',num2str(maxval)]) average = total/ncols; %weekly average disp(['& average is ',num2str(average)]) % Now test for count if maxval >= average + 5 count = count + 1; end %endif end %end outer loop % Display result disp('Number of weeks is:') disp(count)

38 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.

39 39 clear,clc temps = load('temperatures.txt'); %load the data [nweeks ndays] = size(temps); %initial flag for found threeFound = 0; for week = 1:nweeks %outer loop on weeks count = 0; %initial counter for hot days % Inner loop - count days over 80 for day = 1:ndays if temps(week,day) > 80 count = count + 1; %increment count end %endif end %end day loop

40 40 % Check count, exit if done if count >= 3 threeFound = 1; %set flag weekNumber = week;% save the week index break; %break out of week loop end %endif end if threeFound disp('1st week over 80 three times is:') disp(weekNumber) else disp('There were no weeks over 80 three times.') end


Download ppt "1 ECE 1331 MATLAB: Iteration loops and implied loops."

Similar presentations


Ads by Google