CS 211 Lesson 8
Repetition: for Loops
Quote:
I am not bound to win, but I am bound to be true. I am not bound to succeed, but I am bound to live by the light that I have. I must stand with anybody that stands right, stand with him while he is right, and part with him when he goes wrong. Abraham Lincoln
Lesson Objectives:
Know the syntax of the for loop
Be able to use the for loop
Understand when to use a while loop versus a for loop
Understand the purpose of the break and continue statements
Be able to use nested loops
Lesson:
I. MATLAB Concepts
A. Review of loops
There are two primary classifications of loops:
condition-controlled loops
Repeat one or more statements while some condition is true.
In general, when the loop begins, you do not know how many times it will repeat.
A condition-controlled loop in MATLAB is called a while loop.
count-controlled loops
Repeat one or more statements for a fixed number of times.
In general, when the loop begins, you know how many times it will repeat.
A count-controlled loop in MATLAB is called a for loop.
Most loops require a loop control variable that must be initialized, tested, and modified (ITM) to make the loop operate properly.
B. The for loop
The for loop has the following syntax:
for <loop control variable> = <vector expression>
<one or more statements>
endFor example:
for Count = 1:10
fprintf('Count = %d\n', Count');
endThe for loop behaves as follows:
The vector expression (often a vector shortcut expression such as 1:10) is evaluated to form a row vector of values. If the row vector is an empty vector, execution skips to the code following the end (i.e., the loop body is executed zero times). Otherwise, the loop control variable is set to the first element of the row vector and then the code between the vector expression and the end (the loop body) is executed. After execution of the loop body code, the loop control variable is set to the next value in the row vector, if there is one, and the loop body executes again. This sequence repeats until the loop control variable is set to the last value of the row vector and the loop body executes for a final time. Execution then resumes after the end.
The vector expression often has the form first:last or first:increment:last (e.g., 1:10, 100:10:200) but the the vector expression can be any array -- even multi-dimensional arrays. If the vector expression is a multi-dimensional array, the elements are processed in column-major order.
The initial, one-line for statement performs the initialization, testing, and modification (ITM) of the loop control variable !
In most cases, the number of times the loop repeats equals the number of elements in the row vector created from the vector expression.
The vector expression is often created during program execution and therefore the exact number of times a for loop executes is not known until the program runs -- for example:
Max_Number = input('Enter a number to count up to: ');
for Count = 1:Max_Number
fprintf('Count = %d\n', Count')
end
Note that this loop repeats 0 times if the user enters a number less than 1Indenting the lines of the loop body is very important for readability.
In general, your code should never change the value of the loop control variable in the body of the loop.
for loops are commonly used for "processing" each element of an array, for example, the following loop adds 1 to each element of the Vector:
Vector = [5 3 2 6 1 1 4 6 3 2];
for Index = 1:length(Vector)
Vector(Index) = Vector(Index) + 1;
end
disp(Vector);C. Nested loops
Like all control structures, for loops can be nested (one loop placed inside another loop).
Nested loops are commonly used for "processing" each element of multidimensional arrays.
The following example shows how to work with a 2-D matrix using two nested for loops:
Matrix = [6 3 5; 8 4 6; 2 1 9; 7 5 2];
[Num_rows Num_cols] = size(Matrix);
for Row = 1:Num_rows
for Col = 1:Num_cols
fprintf('Element (%d,%d) = %d.\n', Row, Col, Matrix(Row, Col))
end
end
For 3-D arrays, you would use 3 nested loops to process all elements.
D. The break statement
The break statement may be used to terminate a loop from any location in the body of a loop.
When a break statement is executed inside a loop, execution jumps to the code after the end of the loop.
The following code, which will stop repeating once the first occurrence of a "target" value is found, is an example of a loop containing a break statement:
Position = 0; % if Position is 0 when the loop finishes, the target was not found
for Index = 1:length(Vector)
if Vector(Index) == Target
Position = Index;
break
end
endIf you are using a break statement in a for loop, consider re-writing the loop as a while loop. For example, the above for loop can be written as the equivalent while loop below:
Index = 1;
while (Index <= length(Vector)) && (Vector(Index) ~= Target)
Index = Index + 1;
end
if Index <= length(Vector)
Position = Index; % Found the Target value at the Index position
else
Position = 0; % The Target value was not found
endE. The continue statement
The execution of a continue statement in a loop causes execution to jump back to the beginning statement of the loop.
The following code, which skips the processing of all values in an array that are negative, is an example of a loop containing a continue statement:
for Index = 1:length(Vector)
if Vector(Index) < 0
continue
end% process the Vector(Index) element in some way
endThe continue statement is rarely needed and its use should be avoided. For example, the previous code example is better written as
for Index = 1:length(Vector)
if Vector(Index) >= 0
% process the Vector(Index) element in some way
end
end
II. Good Programming Practices
Vertical alignment of statements is very important to make code readable and easily modifiable.
Vertically align, in the same column, corresponding for and end keywords, indenting all statements inside them to the right at least 2 spaces.
You can use MATLAB's smart indent feature (Text ->
Smart Indent or
Ctrl-I) to automatically indent selected code for you.
The loop control variable name should be descriptive to
indicate how it is used in the loop. However, when you use the loop
control variable exclusively as an index into an array, you can use the
single letters I, J, K, M, and N as the loop control variable name
with no loss of readability. (Computer scientists have borrowed these
"names" from mathematicians as commonly acceptable array indices.
For example, ai, bj, ck, etc.)
Use a for statement when you need to repeat a block of code and the exact number of times to repeat the code can be specified by a vector. For example, the two loops below will perform the exact same tasks, but the for loop is preferred over the while loop because the iteration values can be specified as a vector.
for loop (preferred) while loop (don't use in such cases) for J = 1:2:100
% Perform some tasks
endJ = 1;
while J <= 100
% Perform some tasks
J = J + 2;
end
Use a for statement when you need to "process" individual elements of an array in non-uniform ways. For example, the following code subtracts 10 from each element of an array that is larger than 80:
for Index = 1:length(Vector)
if Vector(Index) > 80
Vector(Index) = Vector(Index) - 10;
end
end
Use vector math operations (and not a loop) to "process" individual elements of an array in uniform ways. For example, the following code subtracts 10 from every element of an array:
Vector = Vector - 10;
In general, MATLAB's vector match operations run much faster than equivalent loops and should be used whenever possible. That is,
Don't do this: When this is possible: for Index = 1:length(Vector)
Vector(Index) = Vector(Index) - 10;
endVector = Vector - 10;
III. Algorithms
A. Find the largest value in an array
Algorithm
Assume that the first element is the largest value in the array and store it into a variable called Largest.
Compare every other value in the array to the Largest value and, if a larger value is found, store it into the variable Largest.
Algorithm coded into MATLAB statements
Largest = Vector(1);
for Index = 2:length(Vector)
if Vector(Index) > Largest
Largest = Vector(Index);
end
end
- - use the built-in function max
MATLAB method
Largest = max(Vector);
% or
[Largest Position_of_largest] = max(Vector);
Lab Work: Lab 8
References: Chapman Textbook: section 4.2