sheng/nested for loops
From CDS 130
Contents 
1. Objective
 To introduce nested for loops.
2. Motivation
 Before we can handle images, we need to be able to manipulate matrices.
 Nested for loops is the most basic way a matrix can be manipulated.
3. Prequestion
 What is confusing about for loops?
4. Slides
4.1. Overview
 You were already introduced to nested for loops when we covered Matrices.
 More details are given here.
4.2. Nested objects
4.3. Introduction
for i = [1:3] DO ANYTHING end
for j = [1:2] B(i,j) = 1.0 end 
for i = [1:3] for j = [1:2] B(i,j) = 1.0 end end 
4.4. Evaluation of one for loop
B(1) = 1; for i = [1:3] B(i+1) = 1.0; end To figure out what a loop does, break it down into two columns: Index and Body.


4.5. Evaluation of two for loops
The main change is that there are two indices to keep track of
for i = [1:3] for j = [1:2] B(i,j) = 1.0 end end 

4.6. Evaluation of two for loops
for i = [1:3] for j = [1:2] B(i,j) = 1.0 end end 
Continue incrementing the index in the inner loop

4.7. Question
What is B? Do it by hand and then enter into Octave. for i = [1:2] for j = [1:2] B(i,j) = i+j; end end 

4.8. Question
What is B? Do it by hand and then enter into Octave.
clear B; B(1,1) = 13.0; for i = [2:3] for j = [2:3] B(i,j) = i+j; end end 

4.9. Question
A = [1,2,3 ; 4,5,6 ]
B = [A ; A] or A = [A ; A] what is the difference between the above two options? 
clear A = [1,2,3 ; 4,5,6] for i = [1:3] A = [A ; A] end 
4.10. Answer
 After iteration 1
A = 1 2 3 4 5 6 1 2 3 4 5 6
 After iteration 2
A = 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6
 After iteration 3
A = 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6
5. Questions
These questions are intended to be worked in order, as each question builds on the previous question.
To answer these questions, please refer to your notes from class and the tutorial sent via email.
5.1. Problem 1: Read a nested loop
Consider the following Octave code:
for i=[1:40] for j=[1:40] M(i,j) = (i3)*(j+3); end end
When the above code is run, what are the values in the following locations of the M array? (NOTE: One could solve this problem by hand, given the equation in the above code. I strongly suggest that you run the code instead, for practice.)
M(10,15) = M(12,32) = M(20,21) = M(35,1) = M(40,27) =
5.2. Problem 2: Write a nested loop
Using the M array that you generated in the previous problem, write a nested FOR loop structure in Matlab code that prints out the first five values from rows 22, 23 and 24 of the M array. Show both your Matlab code and the output from running your code.
5.3. Problem 3: Interpreting results
There is one row of the M matrix generated by the MATLAB code in Problem 1 that's filled completely with zeros (that is, the value 0 is stored at all locations in that specific row). Which row is it, and why does each location in this row contain the value zero?
5.4. Problem 4: Filling a matrix
Write Octave code to fill all positions of the row in M that you identified in Problem 3, with the new value 4.5. Ensure that ONLY the values in this particular row are assigned the new value 4.5. Run your Matlab code to demonstrate that positions in this particular row of M now contain the value 4.5 and not 0. Show both your Matlab code and the output from running your code. (NOTE: When solving this problem, you will not require a nested FOR loop: Only one FOR loop will do the job.)
5.5. Problem 5: Interpreting a loop
Which set of nested for loops will produce this matrix?
M = 1 1 1 2 2 2 3 3 3
for j = [1:3] for i = [1:3] M(i,j) = i end end 
for i = [1:3] for j = [1:3] M(i,j) = i end end 
6. Tutorial
By Joeseph Marr 09:14, 5 November 2010 (EDT)
This is a short tutorial on the concept of nested FOR loops, which will be useful for you when we consider image processing. The concept is not difficult, but it involves a bit more "bookkeeping" because now we have two FOR loops executing together, instead of just one FOR loop executing by itself. Furthermore, one of these loops will be INSIDE the other loop, and thus, executes all the way through (i.e., executes fully) for EACH iteration of the outer FOR loop. We'll begin with a simple example and build this example up toward the nested FOR loop structure.
First consider the standard FOR loop that we already know:
for i=[1:5] A(i) = i; end
If we run this code, we will create an array called "A" and fill each of its five positions (15) with a value. That value will be an integer corresponding to the array position: A(1) = 1, A(2) = 2, A(3) = 3, A(4) = 4, and A(5) = 5. Recall that we don't see these values printed to the screen because I intentionally ended the assignment statement with a semicolon, which as we know suppresses output. But, the A array is still in memory, waiting to be used (in Matlab, look in the upper right hand corner of the screen, in the area called "Workspace", and you'll see a small yellow icon there with the name A attachedthus, array A is indeed in memory). If, in a later calculation, we wanted to use the entire array A, we would simply type "A" into a calculation that accepts an array as input, and that calculation would be performed on each element of array A, simultaneously (most arithmetic calculations behave like this, but a few of them require slight modification). Thus, if I wanted to add the integer 5 to each of the elements of array A, and assign the result to an array called "B", I would write the following Matlab statement:
B = A+5
Note that I didn't need to ask for explicit positions like A(1), A(2), etc., to do the addition. Rather, the addition was done "all at once", on the entire array A, with Matlab taking care of the details for us. Of course, we could have done the same thing by adding the integer 5 to each element of A, one at a time, and assigning the result to an array B, like this:
for i=[1:5] B(i) = A(i)+5; end
This accomplishes the same objective.
You might therefore ask why we would EVER consider writing a FOR loop to do an elementbyelement addition like this, when one simple statement, namely, , does the job just fine. We wouldn'tin Matlab! But OTHER computer languages don't take care of all the details for you like Matlab does, so it's good to know how to do the addition element by element.
But, there's more...
One might ALSO want to perform mathematical operations (possibly different) on each of the elements of array A, or to inspect each element of A and perhaps make some sort of decision based on what one finds. That's more sophisticated than just adding the integer 5 to each element of an array. And so, doing sophisticated things may require us to look at each element of an array, one by one. That's a good reason why we need to know how to access array elements one at a time, as shown above.
So far, we've been working with one dimensional arrays, that is, a long string of numbers all lined up in a row. That's what the A and B arrays above areone dimensional arrays. Long strings of numbers. But arrays can be constructed that have more than just one dimension.
The most common type of array in computational science is the two dimensional array. Whereas one dimensional arrays can be thought of as a single row of boxes (each box containing a value), two dimensional arrays can be thought of as a "square filled with boxes". Here's a standard one dimensional array, the A array from above, holding the values we assigned to it with the first FOR loop above:
[1,2,3,4,5]
And now, here's a two dimensional array, which as you can see in this particular case, holds a lot more values:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
The one dimensional array A is known as a "onebyfive" array, or "1x5". This means that there's one row and five columns. The two dimensional array, on the other hand, is known (in this particular case) as a "fivebyfive" array, or "5x5". This means that there are five rows and five columns.
Now in the above Matlab code we accessed locations inside A using a single variablein this case, the letter "i" which the FOR loop assigns the successive values 1, 2, 3, 4 and 5. If later we want to know what value is located in, say, the third location inside A, I simply write "A(3)" and Matlab responds (in this case) with the integer 3:
A(3) ans = 3
Of course, I can use values from any A array location. All I need to do to retrieve the value from a specific A location, is write the name of the array, followed by a left parenthesis, followed by the position number in the array (which has stored in it the value I am seeking), followed by a right parenthesis. Of course, you've been doing this all along in your own Matlab/Octave programs when you wrote statements such as:
A(i+1)=A(i)+0.05*A(i)
When you wrote statements like that, you accessed SPECIFIC array locations, and then, used the values stored in these locations for subsequent computations. The variables "i", "j" and "k" are commonly used in programming to indicate specific array locations. When "i" (or any other variable for that matter) is used in this manner, it is called an "array index variable", or an "array index", or simply an "index". In the examples we've been discussing, "i" has been our array index.
The situation is analogous for two dimensional arrays, but in that case, we vary two variables rather than just one. A square is two dimensional, having a length and a width. Likewise, a two dimensional array has one index for its rows, and another for its columns. Consider the 3x3 array "C". C, being a 3x3 array, has values stored in the following locations: C(1,1), C(1,2), C(1,3), C(2,1), C(2,2), C(2,3), C(3,1), C(3,2) and C(3,3). We will need to use two index variables instead of one to access these C locations because we can make row and column choices independently if we wish. If we let each row be referenced by index variable "i" and each column be referenced by index variable "j", then by choosing appropriate values for i and j, we can access any storage location inside C and retrieve the value at that location.
Similarly, by varying the row and column index variables independently, we can STORE any values we wish INTO specific C array locations. So for example if I wrote the Matlab statement , I would store the value 1.0 INTO the C array, at the position row 1, column 3.
Previously we used one single FOR loop to store values into a onedimensional array. Now we will need two FOR loops because we're dealing with twodimensional arrays. The strategy to store values in the C array will be as follows: In one FOR loop we will vary the index variable "i", to begin at row 1 and move down C's rows one at a time until we get to C's last row. But, each time we increment the variable "i" by one stepthus addressing a new row of Cwe will vary the index variable "j" OVER ALL OF C's COLUMNS. The net effect will be to step down the C array, row by row, and for each row, store values into each of its column positions across that row, from left to right, all the way across, before moving on to the next row.
Here's the Matlab code we would use to fill the 3x3 array C with the value 1.0 in each array position:
for i=[1:3] for j=[1:3] C(i,j) = 1.0 end end
What's going to happen? We'll enter the first FOR loop (or, "outer FOR loop"). When we do, index variable "i" is set to the value 1 (integer 1, not 1.0!). And then the second FOR loop (or, "inner FOR loop") is entered. Remember that index variable "i" still holds the value 1. In the inner FOR loop, index variable "j" is set to the value 1 and the assignment statement , is executed. C(1,1) appears on the left hand side of the assignment statement precisely because index variable "i" currently holds a value of 1, and index variable "j" currently holds a value of 1. The inner FOR loop now begins AGAIN and this time the index variable "j" is set to the value 2, and the assignment statement is executed. C(1,2) appears on the left hand side of this statement because while index variable "i" STILL holds a value of 1 (we're not finished with the outer FOR loop yet!), index variable "j" has had its value reset from 1 to 2 by the inner FOR loop. So in the assignment statement , "i" equals 1 and "j" equals 2. After the assignment statement executes a second time, the inner FOR loop begins AGAIN, resetting its index variable "j" to the value of 3. That means the assignment statement is executed. And now, the inner FOR loop is finished because index variable "j" is only given the values 1, 2 and 3 by the inner FOR loop. At this point, the outer FOR loop has just finished its work for the index variable "i" equal to 1. NOW, the outer FOR loop resets the value of "i" to 2, and, we begin again!
NOTE: When we begin the outer FOR loop again, it's important to realize that the value of index variable "j" will be RESET to 1 by the inner FOR loop, as that loop begins its next execution. It does not retain its old value of 3. Thus, the second time through the inner FOR loop will result in the value 1.0 being assigned to C array positions C(2,1), C(2,2) and C(2,3), corresponding to index variable "i" being set to the value 2 and index variable "j" varied from 1 to 3. You can now guess that the outer FOR loop will execute one final time, with its index variable "i" set to 3, and with inner FOR loop index variable j varied from 1 to 3. And that's exactly what happens. The net effect is that we visit ALL the storage locations in the C array. In this case, when we visit a location, we assign the value 1.0 to that location.
What we've just done is work through a detailed example of a NESTED FOR LOOP structure. This is the basic structure we'll use to access positions inside two dimensional arrays.
Now, not all two dimensional arrays are square, however, like the 3x3 array C. We can have arrays of various shapes. We're already familiar with 1xN arrays, which we've used extensively in our iterative programming exercises. Now it's time to familiarize ourselves with arrays of other dimensions.
For example, let's say we wanted to create a 4x6 array called "D", and fill each of its positions with the value 2.75. How would we write that Matlab code? Like this:
for i=[1:3] for j=[1:3] D(i,j) = 2.75 end end
That's it. That code does the trick. We have four rows. So we vary the outer FOR loop index "i" from 1 to 4. We have six columns. So we vary the inner FOR loop index "j" from 1 to 6. The result is a 4x6 array called "D" that has the value 2.75 assigned to each of its storage locatons. There are 24 total storage locations in D.
Nested FOR loop structures give us a powerful means of addressing individual storage locations inside arrays, and, of performing mathematical operations on the values stored at these locations. In the next short Matlab tutorial we'll use nested FOR loops to step through all the elements of an array and IF statements to make decisions based on the values that we find at each position. To accomplish this, we'll learn some basics about Matlab's IF statement.