You are on page 1of 6

Loops and Implied Loops

ECE 1331 MATLAB: Iteration


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. pass. Looping is also also called iteration.

Loops and Implied Loops


"iterate":
to perform again; repeat
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


Init total to zero Init total to zero For each value in data... no more values

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

Look at next data value

Is value > val?

No Is value > val? next value

No

Yes

Yes Add value to total

Add value to total

Yes

More values in data?

No

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"
3 5 1 -3 8 6 -5 11 =IF(A1>val,A1,"") =IF(A2>val,A2,"") =IF(A3>val,A3,"") =IF(A4>val,A4,"") =IF(A5>val,A5,"") =IF(A6>val,A6,"") =IF(A7>val,A7,"") =IF(A8>val,A8,"")

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

=SUM(B1:B8)

Look closely and see how this is an implementation of the flowchart and pseudocode.

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

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 statements end for loop-variable = aVector 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

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: Fill vector with values of cos(x) for k = 1:101 x = (k-1)*2*pi/100; y(k) = cos(x); end equivalent to:

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

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

x = linspace(0,2*pi,101); y = cos(x);

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 end

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

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

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. 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) the instructions that are executed each pass through the loop 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:

Well-known for Loop examples


Find maximum value in a vector

load data.txt;
Disp. # of neg. values in data array

loop control: initialize, increment/modify, test

data = [3,4,1,-3,8,6,-5,11];

loop body

post-loop cleanup

data = [3,4,1,-3,8,6,-5,11]; % pre-loop counter initialization = 0; counter = 0; for control n = 1:length(data) % loop for n = if 1:length(data) data(n)< 0 % loop body counter = counter + 1 if data(n)< 0 end counter = counter + 1 end end end disp('Number of negative values is: ') % post-loop cleanup disp(counter) disp('Number of negative values is: ') disp(counter)

maximum = data(1); for n = 2:length(data) if data(n)>maximum maximum = data(n); end end

% maximum so far

% replace with new maximum

Of course, there is also a quick function for that: maximum = max(data);

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 end % Display result if(found) disp('Value was found.') else disp('Value was NOT found.') end

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

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

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 end

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

Operational Issues with a FOR


What is value of loop index when loop is complete?

Next Value or Last Value?

0.9

0.8

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 end
0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 -5

10

for n=1:5 disp(n) end disp(n)

Operational Issues with a FOR


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

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

for n=1:-5 disp(n) end disp(n)

General Rule for for Loop


Do NOT explicitly change the control variable inside the loop!

How do we get out of a loop?

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

break;

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

Operational Issues with a for loop Can loop control be a matrix rather than a vector?
A = 1 3 5 2 4 6
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

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

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

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

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)

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)

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.

[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 end disp('Number of times:') disp(count)

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

[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

You might also like