# Iteration

Jump to: navigation, search
Iteration

# 1. Iteration

## 1.1. Objectives

• To introduce the concept of iteration.
• To introduce the concept of an index variable.
• To show how iteration is performed using a for loop or while loop.

## 1.2. Motivation

Almost all computational models of science models require iteration.

In computing, iteration means "repeat calculation". Simulating a model of a physical system usually requires iteration.

For example, suppose the population of the number of rabbits on an island doubles every year and the population was initially 10 rabbits. The population in year 2 could be computed by entering

P = 10;   % Assign to a variable named P the value 10.
P = 2*P;  % Assign to a variable named P the previous value of P times 2.


To compute the population in year 5, the following could be entered

P = 10;   % Year 1
P = 2*P;  % Year 2
P = 2*P;  % Year 3
P = 2*P;  % Year 4
P = 2*P   % Year 5


Note that I have repeated the commands P = 2*P four times. Also recall that MATLAB ignores everything after and including the percent sign.

Suppose you want to compute the population in year 1000 and don't want to type all the commands required to do the computation. There are several types of short-hand syntax for iteration. The most commonly used is the for loop syntax. (In programming, the word "loop" means repeat). The while loop can also be used for iteration. The key task in programming with iteration is finding the parts of the program that can be repeated and re-written using short-hand syntax.

## 1.3. For Loop Basic Pattern

A for loop is short-hand syntax that allows you to re-write a set of statements as something that (usually) requires fewer lines.

 Long-hand pattern: P = 2*P; P = 2*P; P = 2*P; P = 2*P  Short-hand using for loop: for i = [1,2,3,4]  % Line A. P = 2*P;  % Line B. end  % Line C. 

The lines in this statement are interpreted as (MATLAB ignores everything including and after the %):

• Line A: Set an index variable i to the first value in the array [1,2,3,4], which is 1. Note that an index variable does not always have to be i. As long as it is a valid variable, it can be used as an index variable. For example, m, n, b1, J, etc. would all be valid names for an index variable.
• Line B: Do the computation P = 2*P;
• Line C: If all of the possible values of i in the list [1,2,3,4] have been used, end this loop and continue to the next line. Otherwise, repeat everything between the for and end lines again with the next value of i in the list (which is 2).

In this example, there was only one line between the for and end lines. This is not required. Later, we'll put multiple lines between them.

## 1.4. For Loop Basic Pattern

This is an example of replacing a basic pattern with a for loop. Note that the first line does not fit the pattern and cannot be shortened.

 Original program: P = 10; P = 2*P; P = 2*P; P = 2*P; P = 2*P;  Shorthand using for loop: P = 10; for i = [1,2,3,4] P = 2*P; end 

What will happen if you replace i = [1,2,3,4] with i = [7,8,9,10] or i = [1,3,5,7]?

In this case, you will get the same result. The part between the for and end is repeated as many times as there are numbers between the square brackets. In all of these cases, there are four numbers between the square brackets and since the code between the for and end does not reference the index variable i, it does not matter what for numbers are in the square brackets.

As we will see, if the part between the for and end includes a reference to i, the result will not always be the same.

## 1.5. Syntax Rules and Conventions

Rules

• Every for statement must have an associated end statement.
• The for and end statements must be lower case.

Conventions

The for and end are usually aligned vertically. This is allowed:

for i = [1,2,3,4]
P = 2*P;
end


but this is easier (for humans) to read:

for i = [1,2,3,4]
P = 2*P;
end


The repeated part is usually indented. This is allowed:

for i = [1,2,3,4]
a = 1;
end


but this is easier to read:

for i = [1,2,3,4]
a = 1;
end


## 1.6. Basic Pattern Example I

 Original program: x = 10; x = x + 1; x = x + 1; x = x + 1; x = x + 1; x = x + 13;  The middle four statements are repeated four times, so they can be re-written using a for loop: x = 10; for i = [1,2,3,4] x = x+1; end x = x + 13;  Notice the values for the index variable i are different, but this will give the same result: x = 10; for i = [1,5,10,20] x = x+1; end x = x + 13; 

## 1.7. Basic Pattern Example II

 Original program: a = 0; z = a+1; a = z+1; z = a+1; a = z+1;  In this case, there are two lines (each repeated twice) that are repeated so there are two lines between the for and end: a = 0; for i = [1,2] z = a+1; a = z+1; end  The change in values of the index variable will give the same result: a = 0; for i = [99,101] z = a+1; a = z+1; end 

## 1.8. For Loop General Pattern

Thus far, we have used the number of values between the square brackets as an indicator of how many times the repeated part should be repeated. It turns out that what is actually happening when we enter:

for i = [1,2]
P = 2*P;
end


is that MATLAB is executing the commands:

i = 1;
P = 2*P;
i = 2;
P = 2*P;


That is, prior to executing the commands between the for and end, MATLAB is assigning a value to the index variable.

If you see a set of short-hand commands like this:

for i = [19,20]
P = 2*P;
end


internally, MATLAB does the following set of commands:

i = 19;
P = 2*P;
i = 20;
P = 2*P;


Note that the two previous examples would not execute in MATLAB because P has not been assigned a value before the following line in the program, P = 2*P;.

## 1.9. General Pattern Example I

The set of commands on the left are equivalent to the set of commands on the right.

 for i = [1,2,3,4] a = i*i; end  i = 1; a = i*i; i = 2; a = i*i; i = 3; a = i*i; i = 4; a = i*i; 

The set of commands on the left are equivalent to the set of commands on the right.

 for i = [10,11,12,14] a = i*i; end  i = 10; a = i*i; i = 11; a = i*i; i = 12; a = i*i; i = 14; a = i*i; 

Note that the two examples will give different results because the index variable i is referenced in the line between the for and end.

## 1.10. General Pattern Example II

In this example, the first two lines are not repeated, but the rest follows the general pattern of a counter variable being assigned a value and then a statement that appears multiple times.

 i = 1; a = 13; i = 2; a = i*i; i = 3; a = i*i; i = 4; a = i*i;  i = 1; a = 13; for i = [2,3,4] a = i*i; end 

## 1.11. General Pattern Example III

 i = 1; a = 13; i = 2; a = i*i; a = a+1; i = 3; a = i*i; a = a+1; i = 4; a = a+1; a = i*i;  i = 1; a = 13; for i = [2,3,4] a = i*i; a = a+1; end 

In this example, only the part after the first two lines fits the basic pattern and the repeated part takes up two lines. That is, the statements

a = i*i
a = a+1;


are repeated three times.

## 1.12. Populating an Array

We can also use the counter variable inside of the for loop:

clear;
for i = [0,1,2]
B(i+1) = i*i;
end
B


is the same as

clear;
i = 0;
B(i+1) = i*i; % B(0+1) = 0*0, which is B(1) = 0;
i = 1;
B(i+1) = i*i; % B(1+1) = 1*1, which is B(2) = 1;
i = 2;
B(i+1) = i*i; % B(2+1) = 2*2, which is B(3) = 4;


## 1.13. Populating an Array Examples

Problem: Create the array [2,3,4,5]

Answer:

For problems such as this, it is often helpful to first write out the long-hand statements that one would need to execute to create the array:

A(1) = 2
A(2) = 3
A(3) = 4
A(4) = 5


In the above, the numbers on the left hand increment by one and vary from 1-4. So the for loop will need to have the following form:

for i = [1:4]
A(i) = ?
end


The next step is to determine how ? is related to i. In the above it appears that ? is always one larger than i, so the final answer is

for i = [1:4]
A(i) = i+1;
end



Problem: Create the array [5,4,3,2,1]

Answer:

Following the example above, we write

A(1) = 5
A(2) = 4
A(3) = 3
A(4) = 2
A(5) = 1


then

for i = [1:5]
A(i) = ?
end


It appears that the ? is related to i by ? = 6-i, so

for i = [1:5]
A(i) = 6-i
end


## 1.14. An Additional Short-hand

There is a short-hand notation that can be used in for loops. Instead of writing:

for [1,2,3,4,5,6,7,8,9,10]


we can write:

for [1:1:10]


which is read, "Start at 1 and increment in steps of 1. Stop at 10." This notation can also be used to count down.

for [10,9,8,7,6,5,4,3,2,1]


can be written as:

for [10:-1:1]


which is read "Start at 10 and count down in steps of 1. Stop at 1."

Note that the middle number can sometimes be omitted (as covered in Arrays). If it is omitted, it is assumed to be 1.

for [1:10]


is the same as:

for [1:1:10]


## 1.17. Iteration using while

A second method of repeating commands involves the use of the while statement. The loop executes as long as the test condition is true.

while (test)
Execute commands
end


In the following example, the commands P=1.1*P and i = i+1 are repeated provided that P is less than 1000. The last line of the program displays the value which corresponded to the last value of P.

i = 0;
P = 100;
while (P < 1000)
P = 1.1*P;
i = i+1;
end
i


# 2. Problems

## 2.1. Basic pattern

Can any part of the following be re-written using a for loop?

b = 1;
b = b+1;
b = b+1;
b = b+1;


## 2.2. Basic pattern

Can any part of the following be re-written using a for loop?

b = 1;
b = b+1;
c = 2*b;
b = b+1;
c = 2*b;
b = b+1;
c = 2*b;


## 2.3. Syntax

What is wrong with each of the following for loops?

for i = [1,2,
a = i;
end

for j = [1,2,3]
b = 1;
End

for j = [1,2,3]
c = a;
end


## 2.4. Syntax

Are these two sets of commands equivalent?

 i = 1; b = 3+i; i = 2; b = 4+i;  for i = [1,2] b = 3+i; end 

## 2.5. Syntax

What will happen when these commands are executed?

for i = [3,4]
b = 3+i
i
end


## 2.6. Syntax

What will happen when these commands are executed?

for i = [3,4]
i
b = 3+i
end


## 2.7. Syntax

What will happen when these commands are executed?

for i = [1:2:100]
i
end


## 2.8. Syntax

What will happen when these commands are executed? What will the final value of the variable named counter be?

counter = 0;
for i = [3:100]
counter = counter + 1
end


## 2.9. Syntax

The following program contains two errors. Identify the problems that will cause an error message to appear.

clear;
B = [1,2,10,12];
for i = [1:2:11]
a = b(i+1)
end


## 2.10. Evaluate a for loop

What will be displayed when the following program is executed. If an error message is displayed, describe the reason for the error.

clear;
for z = 1:10
x(z)   = z;
y(z+1) = z;
end
x(11) = 0;
x + y


## 2.11. Array boundaries

When the following program is entered,

clear;
A = [1,2,10,12];
for i = [1:2:11]
b = A(i+1)
end


the result is

b =  2
b =  12
??? Index exceeds matrix dimensions.


Explain the reason for the error.

## 2.12. Array boundaries

When the following program is entered into MATLAB,

A = [1:100];
for i = [1:50:101]
b = A(i+1)
end


the result is

b =  2
b =  52


and then an error message is displayed.

Explain the reason for the error.

## 2.13. Long-hand to short-hand

Using a for loop, write the short-hand version of

i = 1;
a = i-13;
i = 2;
a = i-13;
i = 3;
a = i-13;
i = 4;
a = i-13;


## 2.14. Long-hand to short-hand

Using a for loop, write the short-hand version of

q = 37;
q = 1.9;
q = 38;
q = q*10;
q = 39;
q = q*10;
q = 40;
q = q*10;


## 2.15. Long-hand to short-hand

Using a for loop, write the short-hand version of

i = 1;
a = i;
i = 2;
a = i;
i = 3;
a = i;


## 2.16. Short-hand to long-hand

clear;
B = 111;
for j = [1:4]
B = B+1;
end
B = B + 12;


Write the long-hand version of the program to the left.

## 2.17. Short-hand to long-hand

Write the long-hand version of

a = 0;
for z = [1,2,3]
a = a + 1;
end
a = 13;
b = a+1;


## 2.18. Short-hand to long-hand

Write the long-hand version of

for j = [1,2,3,4]
b = j*j;
end


## 2.19. Short-hand to long-hand

Write out the long-hand version of each of the two programs. Use the long-hand version to explain why they give different values for B.

clear;
B = 111;
for q = [1:3]
B = B+1;
end
B = B + 12

clear;
B = 111;
for q = [1:3]
B = B+q;
end
B = B + 12


## 2.20. Interpreting a for loop

What are the values of array B after the following program is executed?

clear;
for i = [1:4]
B(i) = i+1;
end
B


## 2.21. Interpreting a for loop

What is displayed when the following program is executed?

clear;
for i = [-1:2]
C(i+2) = i*i;
end
C


## 2.22. Interpreting a for loop

Write down the values of A(2), A(3), A(4), and A(5) after this loop has executed.

A(1) = 3
for i = [2,3,4,5]
A(i) = i*A(i-1)+i*i
end


## 2.23. Interpreting a for loop

clear;
A(9) = 13;
for i = [10,11,12]
A(i) = A(i-1)+37;
end


What is A(12) and A(1)?

## 2.24. Interpreting a for loop

A(1) = 10;
A(4) = 0;
for i = [2,3,5]
A(i) = A(i-1)+30;
end


What is A(2), A(3), and A(5)?

## 2.25. Interpreting a for loop

Z(1) = 10;
Z(14) = 5;
for i = [3,4,5]
Z(i) = Z(i-2)+50;
end
Z


What are Z(1), Z(2), Z(5), and Z(13) after the following program is executed?

## 2.26. Interpreting a for loop

When the following program is executed, what will be the final value of cx that is displayed?

cx = 100;
for z = [100:109]
cx = cx+2
end
cx


## 2.27. Interpreting a for loop

When the following program is executed, what will be the final value of cx that is displayed?

cx = 0;
for z = [-10:1]
cx = cx+1
end
cx


## 2.28. Interpreting a for loop

In words, describe the computation being performed in the following script. The input is an array A and the output is s. What is the meaning of s with respect to A?

A = randi(10,1,10)
s = 0;
for i = 1:length(A)
s = s + A(i);
end
s


## 2.29. Interpreting a for loop

In words, describe the computation being performed in the following script. The input is an array A and the output is B. What is the meaning of B with respect to A?

clear
A = randi(10,1,10);
B(1) = NaN;
B(length(A)) = NaN; % Why would B(end) not work?
for i = 2:length(A)-1
B(i) = (A(i-1) + A(i) + A(i+1))/3;
end
B


## 2.30. Creating an array using a for loop

Rewrite the following using the a for loop:

A(1) = 1;
A(2) = 2;
A(3) = 3;


## 2.31. Creating an array with a for loop

The following MATLAB statement creates an array with 4 elements

A = [1:2:9]


Write a MATLAB script using a for loop that creates the same array as the MATLAB statement A = [1:2:9].

## 2.32. Creating an array with a for loop

The following MATLAB statement creates an array

A = [1:10:100]


Write a MATLAB script using a for loop that creates the same array.

## 2.33. Creating an array with a for loop

Using a single for, create the array

[10,9,8,7,6,5,4,3,2,1]


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

Hint: write out the statements that you would have to enter to do this without a for loop first, e.g., A(1)=10, etc. Then convert what you wrote to a for loop.

## 2.34. Modifying matrix elements

6 5 4 1 2 3
6 5 4 1 2 3
6 5 4 1 2 3
1 1 1 1 1 1


Suppose that you named the matrix above as M. Write a single for loop that will set all of the numbers in the last row equal to 3.

## 2.35. Computation using for loop

Write a for loop that adds all of the elements an array of arbitrary length. Do not use the function sum.

## 2.36. Computation using for loop

Your bank balance grows by an amount of 5% compounded yearly. Your initial deposit is $100. After 1 year, you deposit an additional$10. What is your balance after 4 years and one day have elapsed? State any assumptions made for the calculation.

## 2.37. Computation using for loop

Write a for loop that multiplies all of the elements in the array A = [1,2,3,4,5]. Do not use the function prod.

## 2.38. Computation using for loop

Write a for loop that computes the sum of the squares of all elements in an array. For example, if the array is A = [1,2,3,4,5], the sum should be 1 + 4 + 9 + 16 + 25 = 55. Do not use the functions sum or the operator .^. Your code should work for an array of any length.

## 2.39. If statement in loop

What do you expect to happen if you execute this?

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

if (A(i) > 2)
A(i) = 0;
else
A(i) = 1;
end

end


## 2.40. If statement in loop

What do you expect to happen if you execute this?

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


## 2.41. If statement in loop

What do you expect to happen if you execute this?

M = [ 1, 2 ; 3, 4 ];
for j = [1:2]
for i = [1:2]

if (M(i,j) > 2)
M(i,j) = 0;
else
M(i,j) = 1;
end

end
end


## 2.42. If Statement in loop

What will matrix M look like when the following is executed?

clear
B = rand(5,3)
for i = [1:5]
for j = [1:3]
if B(i,j) < 0.5 % selecting values of B to change
B(i,j) = -1.0; % changing the selected B element to a new value
end % end of the if statement
end
end
B

• What are the values of matrix B before the nested for loops?
• What does the rand function do?
• What are the values of matrix B after the nested for loops?
• Change the program using at least two if statements so 1) values above 0.75 are set to 1.0; and 2) values below 0.25 are set to 0.00.

## 2.43. If Statement in loop

1. What is A after the following is executed?
2. Rewrite the code below using a for loop.
A = [1,2,3,4,5];

i = 1;
if (A(i) > 2)
A(i) = 0;
else
A(i) = 1;
end
i = 2;
if (A(i) > 2)
A(i) = 0;
else
A(i) = 1;
end
i = 3;
if (A(i) > 2)
A(i) = 0;
else
A(i) = 1;
end
i = 4;
if (A(i) > 2)
A(i) = 0;
else
A(i) = 1;
end
i = 5;
if (A(i) > 2)
A(i) = 0;
else
A(i) = 1;
end
A


## 2.44. If statement in a loop

Given an array with 5 elements that are either 0 or 1, write a program that implements the following algorithm:

Replace any 0 with a 1.

Modify this program so that it replaces any zero with the element number where it was found. For example, if the array was:

A = [1, 1, 1, 0, 0]


the modified array should be:

A = [1, 1, 1, 4, 5]


because the last two zeros were the fourth and fifth elements of the original array.

# 3. Activities

## 3.1. Introduction to Iteration

In this in-class activity, you will learn a bit about MATLAB syntax.

In addition, the problem you work will prepare you for the next MATLAB task - to write a program that uses iteration.

### 3.1.1. Part I

Before starting MATLAB, work the following problem by hand on paper.

The population of rabbits on an island is 10 at the start of year 1. A biologist has predicted that the population doubles every year.

If you enter on the MATLAB command line

p = 10


corresponding to the population at the start year 1, MATLAB interprets this to mean that you want to assign the value of 10 to the variable named p .

If you then enter

p = p*2


MATLAB will interpret this statement as, "Assign the value of p to the current value of p times 2" and display the new value of p, which is 20. This is the population at the start of the second year.

Question Suppose that you next entered

p = p*2


what do you expect MATLAB to display? _____________

Now suppose that you entered

clear


and then entered

p = p*2


What do you think will be the result? ____________

### 3.1.2. Part II

Start MATLAB and enter the statements from Part I on its command line.

Use MATLAB to compute the population of rabbits at the start of the 10th year.

Write your answer here: __________

### 3.1.3. Part III

Suppose the initial population of rabbits was 6 at the start of the first year. Use MATLAB to determine the population at the start of the 10th year.

Use MATLAB to compute the population of rabbits at the start of the 20th year.

Write your answer here: _________

### 3.1.4. Part IV

(I'll stop the class and show you how to do this. Feel free to try this before I give instructions!)

Entering commands on the command line can be tedious. An alternative way to achieve the same result is to type the commands into a file (MATLAB calls these "m" files because their name ends with ".m").

Open a file and name it rabbits. Copy and paste the following into the file

p = 10
p = p*2
p = p*2
p = p*2
p = p*2


Now select the green "play" button. The effect is the same as if you had entered in the above lines one-by-one at the command line.

Now put a semicolon (;) at the end of each of the lines you pasted into the file (except for the last one).

Why do you see less text displayed?

What do you expect to see if you put a semicolon at the end of the last line? Try it.

### 3.1.5. Part V

Compute the population of rabbits in year 20 by entering commands into your "m" file. Do this for the case where the initial population was 6 and then do it for the case of an initial population of 10. (Hint - to get an answer for an initial population of 10, you only need to modify one line of the program that does the computation for an initial population of 6.)

### 3.1.6. Part VI

(I'll stop the class and give you instructions before you start this. If you finish the previous parts early, see if you can figure out how to change the programs you wrote so that the number 2 only appears once in your m file.)

Create a new file named rabbitsIteration. Use a for loop to compute the population of rabbits at the start of year 20 assuming an initial population of 10. Compare your answer to that obtained previously.

## 3.2. Computing Limits

### 3.2.1. Part I

Write out the long-hand version of this program on paper. What will be the value of a after the program is executed?

a = 1/13
for i = [3,4,5]
a = a + 1/i
end


Write out the long-hand version of this program on paper. What will be the value of a after the program is executed?

a = 1/13
for i = [5,4,3]
a = a + 1/i
end


### 3.2.2. Part II

Based on your answer to the previous problem, do you expect these two programs to give the same result?

a = 1/13
for i = [1,2,3,4,5,6,7,8,9,10]
a = a + 1/i
end

a = 1/13
for i = [10,9,8,7,6,5,4,3,2,1]
a = a + 1/i
end


### 3.2.3. Part III

Should the following two programs give the same answer? Do they?

What happens if you replace the 1000 in both programs with 100000 or 10000000? (The format long statement tells the program to display more decimal places than the default.)

a = 1/13;
for i = [1:1000]
a = a + 1/i;
end
format long
a

a = 1/13;
for i = [1000:-1:1]
a = a + 1/i;
end
format long
a


# 4. Overview Video

An older video that covers some of the same issues is available at [1].