# Nested For Loops

Jump to: navigation, search

# 1. Nested For Loops

## 1.1. Objective

• To introduce nested for loops.

## 1.2. Motivation

• Before we can handle images, we need to be able to manipulate matrices.
• Nested for loops are the most basic way a matrix can be manipulated.

## 1.3. Introduction

A for loop does this:

c = 0;
for i = [1:3]

Do something

end


Previously the Do something part was a command such as c = c+1 that was to be repeated 3 times. The Do something part can be another for loop:

for j = [1:2]
c = c+1;
end


Putting the two together gives:

c = 0;
for i = [1:3]

for j = [1:2]
c = c+1;
end

end


In the code above, the program executes the bolded code three times. The first step in working out what happens is to expand the inner for loop:

c = 0;
for i = [1:3]

j = 1;
c = c+1;
j = 2;
c = c+1;

end


The second step is to expand the outer loop. In this case, the set of four commands will be repeated three times:

 c = 0;
i = 1;
j = 1;
c = c+1;
j = 2;
c = c+1;
i = 2;
j = 1;
c = c+1;
j = 2;
c = c+1;
i = 3;
j = 1;
c = c+1;
j = 2;
c = c+1;


The third step is to replace variables with numbers and to do the computation on the right-hand-side of each equation:

 c = 0;
i = 1;
j = 1;
c = c+1; % c = 0 + 1 = 1;
j = 2;
c = c+1; % c = 1 + 1 = 2;
i = 2;
j = 1;
c = c+1; % c = 2 + 1 = 3;
j = 2;
c = c+1; % c = 3 + 1 = 4;
i = 3;
j = 1;
c = c+1; % c = 4 + 1 = 5;
j = 2;
c = c+1; % c = 5 + 1 = 6;


## 1.4. Creating a matrix with a nested for loop

A nested for loop can be used to populate a matrix: a for loop repeats the commands between the for and end as many times as there are elements in the index variable array. This for loop will execute the commands Do something three times, each time with a different value of i:

for i = [1:3]

Do something

end


The Do something part can have multiple commands or even another for loop:

for j = [1:2]
B(i,j) = 1.0
end


Putting the two together gives:

for i = [1:3]

for j = [1:2]
B(i,j) = 1.0
end

end


## 1.5. Example

To determine the long-hand version of the commands executed by a nested for loop, re-write the original program long-hand form in two steps. First, re-write the inner for loop as long-hand and leave the outer loop as is. Then, re-write the outer part in long-hand form.

What will matrix B look like after you run the program?

for i = [1:3]

for j = [1:2]
B(i,j) = 1.0
end

end


## 1.6. Example

What is B? Do it by hand and then enter into MATLAB to verify the answer. Important: Write out long-hand version on paper first!

for i = [1:2]
for j = [1:2]
B(i,j) = i+j;
end
end


## 1.7. Example

What are the values of B after the following program is executed? Do it by hand and then enter into MATLAB to check your answer.

clear B;
B(1,1) = 13.0;
for i = [2:3]
for j = [2:3]
B(i,j) = i+j;
end
end


## 1.8. Example

Previously we discussed how a matrix could be created with this notation, which "stacks" the row of numbers 1 2 3 on top of the row of numbers 4 5 6.

A = [1,2,3 ; 4,5,6 ]


Matrices can be "stacked" too

B = [A ; A]


or

A = [A ; A]


What is the difference between the above two options?

Predict what will happen when this program is run

clear
A = [1,2,3 ; 4,5,6]
for i = [1:3]
A = [A ; A]
end


## 1.9. Example

• Original program:

for i = [1:3]

for j = [1:2]
B(i,j) = i;
end

end

• Modify the program to the left (original program) so that it creates a matrix B with values of:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3

• Modify the program to the left (original program) so that it creates a matrix B with values of:
1 2 3
1 2 3
1 2 3

• Extra credit: Modify the program to the left (original program) so that it creates a matrix B with values of:
1 2 3
2 4 6
3 6 9


# 2. Problems

These questions are intended to be worked in order, as each question builds on the previous question. To answer these questions, please refer to Nested_For_Loops#Slides, your notes from class, and Nested_For_Loops#Tutorial.

## 2.1. Short-hand to long-hand I

• Re-write the nested for loop program given below in long-hand form in two steps. First, re-write the inner for loop in long-hand and leave the outer loop as is. Then, re-write the outer part in long-hand form.
• What will be the final value of c after you run the program?
• Original program
c = 10;
for i = [1:2]

for j = [3:4]
c = c + 2.0;
end

end

• Step 1: Fill in the space below with the long-hand version of the inner for loop.
for i = [1:2]

end

• Step 2: Fill in the space below with the long-hand version of what you wrote for step 2 (specifically write out the long-hand version of the outer for loop). Check your answer by running your program to see if you get the same matrix B as that when running the original nested for loop program.

## 2.2. Short-hand to long-hand II

• Re-write the nested for loop program given below in long-hand form in two steps. First, re-write the inner for loop in long-hand and leave the outer loop. Then, re-write the outer part in long-hand form.
• What will the matrix B look like after you run the program?
• Original program

for i = [2:3]

for j = [1:2]
B(i,j) = 1.0
end

end

• Step 1: Fill in the space below with the long-hand version of the inner for loop.
for i = [2:3]

end

• Step 2: Fill in the space below with the long-hand version of what you wrote for step 2. Check your answer by running your program to see if you get the same matrix B as that when running the original nested for loop program.

## 2.3. Interpreting a loop I

Which set of nested for loops will produce the matrix M?

• A.
• B.
• C.
• D.
• All of the above.
• None of the above.
M =
1 2 3
4 5 6
7 8 9

 A. for j = [1:3] for i = [1:3] M(i,j) = i+j; end end  B. for i = [1:3] for j = [1:3] M(i,j) = i-j; end end  C. for i = [1:3] for j = [1:3] M(i,j) = i end end  D. for i = [1:3] for j = [1:3] M(i,j) = i*j end end 

## 2.4. Interpreting a loop II

Which matrix will result from evaluating the nested for loop below?

• A.
• B.
• C.
• D.
• All of the above.
• None of the above.
counter = 1;
for j = [1:3]
for i = [1:3]
M(i,j) = counter;
counter = counter + 1;
end
end

 A. M = 1 1 1 2 2 2 3 3 3  B. M = 1 2 3 4 5 6 7 8 9  C. M = 1 4 7 2 5 8 3 6 9  D. M = 9 6 3 8 5 2 7 4 1 

## 2.5. Interpreting a loop III

Which matrix will result from evaluating the nested for loop below?

• A.
• B.
• C.
• D.
• All of the above.
• None of the above.
clear M;
counter = 1;
for j = [1:3]
for i = [1:3]
M(i,j) = i+j;
counter = counter+1;
end
end

 A. M = 1 4 7 2 5 8 3 6 9  B. M = 1 2 3 2 4 6 3 6 9  C. M = 9 6 3 8 5 2 7 4 1  D. M = 2 3 4 3 4 5 4 5 6 

## 2.6. Interpreting a loop

Which matrix will result from evaluating the nested for loop below?

• A.
• B.
• C.
• D.
• All of the above.
• None of the above.
clear M;
counter = 1;
for j = [1:3]
for i = [1:3]
M(i,j) = counter+j;
counter = counter+1;
end
end

 A. M = 1 4 7 2 5 8 3 6 9  B. M = 1 2 3 2 4 6 3 6 9  C. M = 2 6 10 3 7 11 4 8 12  D. M = 2 3 4 3 4 5 4 5 6 

## 2.7. Interpreting a Loop V

What are the values in the matrix M after executing this program?

for j = [-1:1]
for i = [0:1]
M(i+1,j+2) = j;
end
end
M


## 2.8. Interpreting a Loop VI

If you typed

for j = [1:3]
for i = [1:3]
M(i,j) = i;
end
end


and then

M(4,3)


on the command line, what do you expect to see?

## 2.9. Interpreting a Loop VII

What are the values in the matrix M after executing this program?

M(1,1) = 37;
for j = [0:3]
for i = [0:3]
M(i+1,j+1) = i;
end
end
M


## 2.10. Interpreting a loop VIII

Consider the following MATLAB code:

for i = [1:40]
for j = [1:40]
M(i,j) = (i-3)*(j+3);
end
end


When the above code is run, what are the values in the following locations of the M array?

M(10,15)
M(12,32)
M(20,21)
M(35,1)
M(40,27)


## 2.11. Write a nested loop

Create a file called nested.m and enter the commands from the previous problem in it. Below these commands, write a nested for loop that prints out the first five values from rows 22, 23 and 24 of M. Execute the commands by typing nested on the command line. On the sheet that you turn in, write out your code and the output from running it.

## 2.12. Interpreting a loop IX

Video Solution: http://youtu.be/xuxOGpZ7h4Y

Which matrix will result from evaluating the nested for loop?

 A. B. C. D. All of the above. None of the above. clear counter = 0; for j = [2:2:4] for i = [1:3] M(i,j) = counter; counter = counter+1; end end M counter 
 A. M = 0 1 2 3 4 5 6 7 8 9 10 11  B. M = 6 0 0 3 0 1 2 4 8 2 2 5 3 4 5 0  C. M = 0 0 0 3 0 1 0 4 0 2 0 5  D. M = 0 0 0 0 1 2 0 0 0 3 4 5 

## 2.13. Nested for loops

Video solution: http://youtu.be/LmEzMCfF0rs

Original program:

for j = [1:10]

for i = [1:10]
B(j,i) = i+j;
end

end


Modify the original program so that it creates a matrix B with values of:

4 4 4 4 4 4
3 3 3 3 3 3
2 2 2 2 2 2
1 1 1 1 1 1


Modify the original program so that it creates a matrix B with values of:

-5 -4 -3
-5 -4 -3
-5 -4 -3


Modify the original program so that it creates a matrix B with values of:

 1 0 0
0 4 0
0 0 9


## 2.14. Nested for loops

• Original program:

for i = [1:3]
for j = [1:3]
Z(i,j) = 1.0;
end
end

• Modify the program to the left (original program) so that it creates a matrix Z with values of:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3

• Modify the program to the left (original program) so that it creates a matrix Z with values of:
1 2 3
1 2 3
1 2 3

• Extra credit: Modify the program to the left (original program) so that it creates a matrix Z with values of:
1 2 3
2 4 6
3 6 9


## 2.15. Nested for loop

Video solution: https://www.youtube.com/watch?v=o6BBD7n_jjo

 B = 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 

Write a program that creates this matrix using nested for loops.

## 2.16. Double for Loop

Video Solution: http://youtu.be/RlBvgFf8BEM

 If you typed clear; for j = [1:3] for i = [1:j] M(i,j) = i; end end  and then entered M(3,3) on the command line and then hit enter, what do you expect to see displayed on the screen? if you then entered M(3,2) on the command line and hit enter, what do you expect to see displayed on the screen?

## 2.17. Creating a matrix

When entering the following commands

clear M
M(2,4) = 10.0


there is one row of the matrix M 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? (The command clear M deletes any previously defined matrix M.)

Write MATLAB code to fill all positions of the row in M that you identified in the previous problem with the new value 4.5. Ensure that only the values in this particular row are assigned the new value 4.5. Run your program to verify that positions in this particular row of M now contain the value 4.5 and not 0. Show both your Matlab/Octave program and the output from running your it. (Note: You can solve this problem with only one for loop.)

## 2.18. Creating a matrix

Use one or more for loops to create the following matrix.

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8


Save your answer in a file named HW3d.m.

Do not use the colon operator inside of the for loop (corresponding to anywhere between the lines containing for and end).

## 2.19. Creating a matrix

Use one or more for loops to create the following matrix.

8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7
6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1


Do not use the colon operator inside of the for loop (corresponding to anywhere between the lines containing for and end). Do not use any MATLAB built-in functions (e.g., flipud).

Save your answer in a file named HW3e.m.

## 2.20. Creating a matrix

Create a 10x10 matrix of all zeros except with diagonal elements of 1,4,9,16,25,36,49,64,81,100, e.g.,

1 0 0 ...
0 4 0
0 0 9
.
.
.


Do not use the colon operator inside of the for loop (corresponding to anywhere between the lines containing for and end).

## 2.21. Creating a matrix

Write a program that produces the following matrix.

M =

2     3     4     5     6     7     8     9
3     4     5     6     7     8     9    10
4     5     6     7     8     9    10    11
5     6     7     8     9    10    11    12
6     7     8     9    10    11    12    13
7     8     9    10    11    12    13    14
8     9    10    11    12    13    14    15
9    10    11    12    13    14    15    16


## 2.22. Creating a matrix

Write a set of commands that will create the following matrix.

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8


Suppose that you named the matrix above M. Write a for loop that will set all of the values in the first row equal to zero.

## 2.23. Redundant loop

Write a program that produces the same matrix using a single for loop.

for i = 1:5
for j = 1:5
if (i == 1)
M(i,j) = i;
end
if (i == 5)
M(i,j) = i;
end
end
end


## 2.24. Transpose

Write a program that transposes a matrix using a double for loop. Your program should work for a matrix of any size.

## 2.25. flipud

Write a program that does the same thing as the function flipud using a double for loop. Your program should work for a matrix of any size.

## 2.26. Matrix inspection

Each element in a matrix can be said to have eight neighbors. For example, the neighbors of the element in row 2, column 2 in the following matrix has neighbors with values of 1,2,3,7,9,4,5,6.

 1 2 3 4 5 6
7 8 9 1 2 3
4 5 6 7 8 9
1 2 3 4 5 6
7 8 9 1 2 3
4 5 6 7 8 9


Write a program that starts with an arbitrary NxN matrix and creates a new matrix that indicates the sum of the neigbors of each non-border element in the original matrix. For example, two elements in the new matrix associated with the above matrix would be

Mnew(2,2) = 1 + 2 + 3 + 7 + 9 + 4 + 5 + 6


and

Mnew(2,3) = 2 + 3 + 4 + 8 + 1 + 5 + 6 + 7


In the new matrix, the border elements (first row, last row, first column, last column) should be zero.

You may test your program by using the function M = randi(9,N) to create a NxN matrix of random integers in the range 1 through 9.

Have your code count the sum of the neigbors of the border elements. For example,

Mnew(1,1) = 2 + 8 + 7


and

Nnew(6,1) = 7 + 8 + 5


## 2.27. Matrix inspection

M = randi(5,5);


Use a for loop to compute the average of all elements in M. Do not use the functions mean or sum.

Use a for loop to create a matrix Mr that has a value of 1 where corresponding elements in M are greater than is average and 0 where the corresponding elements in M are less than or equal to this average.

For example, the matrix

M =
1     5     4     1     3
2     3     4     3     3
4     3     2     4     1
3     5     3     5     2
2     2     1     1     1


has an average value of 2.72, so

Mr =
0     1     1     0     1
0     1     1     1     1
1     1     0     1     0
1     1     1     1     0
0     0     0     0     0


## 2.28. Triple for loop I

When the following is executed, describe what will be shown on the screen. (Note that the line counter = counter+1 does not have a semi-colon a the end.)

counter = 1;
for i = [1:32]
for j = [1:32]
for k = [1:2]
counter = counter+1
end
end
end


## 2.29. Triple for loop II

When the following is executed, describe what will be shown on the screen. (Note that the line counter = counter+1 does not have a semi-colon at the end.)

counter = 1;
for i = [1:10]
for j = [1:10]
for k = [1:10]
counter = counter+1
end
end
end


## 2.30. Single index notation in a for loop

Enter the following commands (note that there is not a semicolon after the 12):

clear;
M = [0, 0 ; 0, 0 ; 0, 1];
for i = [1:6]
M(i) = 12
end


and explain what happens and explain why it happens.

## 2.31. for loop speed

The following program creates an array with N elements and the time to do the operation is stored in a variable named t.

tic
A = [1:N];
t = toc;


Write a program that creates the same array using a for loop. Use the functions tic and toc to create a plot of the time to create the array A versus N using both methods. Your plot should have two lines and a legend with appropriate labels and the axes should have appropriate labels. Choose sensible values of N. Describe the nature of each curve (linear, quadratic, exponential, etc.).

Save your answer in a file named HW3EC1.m.