Iteration
From ComputingForScientists
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 orwhile
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 shorthand 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 rewritten using shorthand syntax.
1.3. For Loop Basic Pattern
A for
loop is shorthand syntax that allows you to rewrite a set of statements as something that (usually) requires fewer lines.
Longhand pattern: P = 2*P; P = 2*P; P = 2*P; P = 2*P 
Shorthand using 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 is1
. Note that an index variable does not always have to bei
. 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 thefor
andend
lines again with the next value ofi
in the list (which is2
).
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 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 associatedend
statement.  The
for
andend
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 rewritten using a x = 10; for i = [1,2,3,4] x = x+1; end x = x + 13; 
Notice the values for the index variable 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 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 shorthand 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 longhand 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 14. 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 ? = 6i
, so
for i = [1:5] A(i) = 6i end
1.14. An Additional Shorthand
There is a shorthand 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.15. break
1.16. continue
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 rewritten using a for
loop?
b = 1; b = b+1; b = b+1; b = b+1;
Answer 

The line 
2.2. Basic pattern
Can any part of the following be rewritten using a for
loop?
b = 1; b = b+1; c = 2*b; b = b+1; c = 2*b; b = b+1; c = 2*b;
Answer 

The two lines 
2.3. Syntax
What is wrong with each of the following for
loops?
for i = [1,2, a = i; end
Answer 

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

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

The variable j = 1; c = a; j = 2; c = a; j = 3; c = a; 
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 
Answer 

These two sets of commands are not equivalent. To make them equivalent, the command on the left should have read: 
i = 1; b = 3+i; i = 2; b = 3+i; 
2.5. Syntax
What will happen when these commands are executed?
for i = [3,4] b = 3+i i end
Answer 

i = 3 b = 3+3 %b = 6 i = 3 i = 4 b = 3+4 %b = 7 i = 4 
2.6. Syntax
What will happen when these commands are executed?
for i = [3,4] i b = 3+i end
Answer 

i = 3 i = 3 b = 3+i %b=6 i = 4 i = 4 b = 3+i %b=7 
2.7. Syntax
What will happen when these commands are executed?
for i = [1:2:100] i end
Answer 

i = 1 i = 1 i = 3 i = 3 i = 5 i = 5 . . . i = 99 i = 99 
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
Answer 

Note that i = 3 counter = 1 i = 4 counter = 2 i = 5 counter = 3 i = 6 counter = 4 i = 7 counter = 5 . . . i = 99 counter = 97 i = 100 counter = 98 Final value of counter is 98 
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
Answer 


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
Answer 

x = [1,2,3,4,5,6,7,8,9,10,0] z = [0,1,2,3,4,5,6,7,8,9 ,10] x + z = [1,3,5,7,9,11,13,15,17,19,10] 
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.
Answer 

When 
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.
Answer 

When 
2.13. Longhand to shorthand
Using a for
loop, write the shorthand version of
i = 1; a = i13; i = 2; a = i13; i = 3; a = i13; i = 4; a = i13;
Answer 

for i = [1:4] a = i13; end 
2.14. Longhand to shorthand
Using a for
loop, write the shorthand version of
q = 37; q = 1.9; q = 38; q = q*10; q = 39; q = q*10; q = 40; q = q*10;
Answer 

q = 37; q = 1.9; for q = [38:40] q = q*10; end 
2.15. Longhand to shorthand
Using a for
loop, write the shorthand version of
i = 1; a = i; i = 2; a = i; i = 3; a = i;
Answer 

for i = [1:3] a = i; end 
2.16. Shorthand to longhand
clear; B = 111; for j = [1:4] B = B+1; end B = B + 12;

Write the longhand version of the program to the left.

2.17. Shorthand to longhand
Write the longhand version of
a = 0; for z = [1,2,3] a = a + 1; end a = 13; b = a+1;
Answer 

a = 0; z = 1; a = a+1; z = 2; a = a+1; z = 3; a = a+1; a = 13; b = a+1; 
2.18. Shorthand to longhand
Write the longhand version of
for j = [1,2,3,4] b = j*j; end
Answer 

j = 1; b = j*j; j = 2; b = j*j; j = 3; b = j*j; j = 4; b = j*j; 
2.19. Shorthand to longhand
Write out the longhand version of each of the two programs. Use the longhand 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
Answer 

Work to get answer: i = 1; B(i) = i+1; %B(1) = 1+1, B(1) = 2 i = 2; B(i) = i+1; %B(2) = 2+1, B(2) = 3 i = 3; B(i) = i+1; %B(3) = 3+1, B(3) = 4 i = 4; B(i) = i+1; %B(4) = 4+1, B(1) = 5 Final array: B = [2 3 4 5] % Other ways to write array B: B = [2, 3, 4, 5], B = [2:1:5], or B = [2:5] 
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
Answer 

Work to get answer: i = 1 C(i+2) = i*i; %C(1) = 1*1 = 1 i = 0 C(i+2) = i*i; %C(2) = 0*0 = 0 i = 1 C(i+2) = i*i; %C(3) = 1*1 = 1 i = 2 C(i+2) = i*i; %C(4) = 2*2 = 4 What will be displayed: C = [1 0 1 4] 
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(i1)+i*i end
Answer 

i = 2 A(i) = i*A(i1)+i*i %A(2) = 2*3+2*2 = 10 i = 3 A(i) = i*A(i1)+i*i %A(3) = 3*10+3*3 = 39 i = 4 A(i) = i*A(i1)+i*i %A(4) = 4*39+4*4 = 172 i = 5 A(i) = i*A(i1)+i*i %A(5) = 5*172+5*5 = 885 
2.23. Interpreting a for
loop
clear; A(9) = 13; for i = [10,11,12] A(i) = A(i1)+37; end
What is A(12)
and A(1)
?
Answer 

The second line creates a 9element array, Work: i = 10 A(i) = A(i1)+37; %A(10) = 13+37 = 50 i = 11 A(i) = A(i1)+37; %A(11) = 50+37 = 87 i = 12 A(i) = A(i1)+37; %A(12) = 87+37 = 124 Answer:

2.24. Interpreting a for
loop
A(1) = 10; A(4) = 0; for i = [2,3,5] A(i) = A(i1)+30; end
What is A(2)
, A(3)
, and A(5)
?
Answer 

Work inside the i = 2 A(i) = A(i1)+30; %A(2) = 10+30 = 40 i = 3 A(i) = A(i1)+30; %A(3) = 40+30 = 70 i = 5 A(i) = A(i1)+30; %A(5) = 0+30 = 30 Answer:

2.25. Interpreting a for
loop
Z(1) = 10; Z(14) = 5; for i = [3,4,5] Z(i) = Z(i2)+50; end Z
What are Z(1)
, Z(2)
, Z(5)
, and Z(13)
after the following program is executed?
Answer 


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
Answer 

z = 100 cx = cx+2 %cx = 100+2 = 102 z = 101 cx = cx+2 %cx = 102+2 = 104 z = 102 cx = cx+2 %cx = 104+2 = 106 z = 103 cx = cx+2 %cx = 106+2 = 108 z = 104 cx = cx+2 %cx = 108+2 = 110 z = 105 cx = cx+2 %cx = 110+2 = 112 z = 106 cx = cx+2 %cx = 112+2 = 114 z = 107 cx = cx+2 %cx = 114+2 = 116 z = 108 cx = cx+2 %cx = 116+2 = 118 z = 100 cx = cx+2 %cx = 118+2 = 120 The final value: 
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
Answer 

Work: z = 10 cx = cx+1 %cx = 0+1 = 1 z = 9 cx = cx+1 %cx = 1+1 = 2 z = 8 cx = cx+1 %cx = 2+1 = 3 z = 7 cx = cx+1 %cx = 3+1 = 4 z = 6 cx = cx+1 %cx = 4+1 = 5 z = 5 cx = cx+1 %cx = 5+1 = 6 z = 4 cx = cx+1 %cx = 6+1 = 7 z = 3 cx = cx+1 %cx = 7+1 = 8 z = 2 cx = cx+1 %cx = 8+1 = 9 z = 1 cx = cx+1 %cx = 9+1 = 10 z = 0 cx = cx+1 %cx = 10+1 = 11 z = 1 cx = cx+1 %cx = 11+1 = 12 Final value: 
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
Answer 

The variable s is the sum of the elements in s = sum(A) 
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(i1) + A(i) + A(i+1))/3; end B
Answer 

The array This program is equivalent to B = filter([1,1,1]/3,1,A); B = [NaN,B(3:end),NaN]; To see visually the smoothing effect, consider clear A = randn(1,100); B(1) = NaN; B(length(A)) = NaN; % Why would B(end) not work? for i = 2:length(A)1 B(i) = (A(i1) + A(i) + A(i+1))/3; end plot(A);hold on;plot(B);legend('Original','3point sliding boxcar'); 
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;
Answer 

for i = [1:3] A(i) = i; end 
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]
.
Answer 

If you don't "see" the answer to a problem like this immediately, try writing out in longhandform what you would need to enter: A(1) = 1 A(2) = 3 A(3) = 5 A(4) = 7 A(5) = 9 then look at the numbers on the lefthandside and try to come up with a relationship with the numbers on the righthandside. In this case, it looks like the numbers on the right are about 2x the numbers on the left. If one subtracts off 1, you get the correct result. for i = [1:4] A(i) = 2*i1; end or a = 1 for i = [1:4] a = a+2; A(i) = a; end How would you solve this using for i = [1:2:9] % ??? end To answer the above, write it out longhand: A(y) = i; % i = 1 A(y) = i; % i = 3 A(y) = i; % i = 5 A(y) = i; % i = 7 A(y) = i; % i = 9 where 
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.
Answer 

To determine the A(1) = 10 A(2) = 9 A(3) = 8 ... A(10) = 1 The number on the right is (11  number on right). So the for i = 1:10 A(i) = 11i; end or for i = [10:1:1] A(11i) = i; end or c = 10; for i = [1:10] A(i) = c; c = c1; end 
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
.
Answer 

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
Answer 

A = [1,2,3,4,5]; i = 1 if (A(i) > 2) %A(1) = 1 => Is 1 > 2? => False A(i) = 0; %This statement is not executed because the Since there are semicolons after each statement, nothing will be displayed. 
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
Answer 

M = [ 1,2 ; 3,4 ]; j = 1 i = 1 M(i,j) %M(1,1) = 1 i = 2 M(i,j) %M(2,1) = 3 j = 2 i = 1 M(i,j) %M(1,2) = 2 i = 2 M(i,j) %M(2,2) = 4 Since there is no semicolon after the 
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
Answer 

M = [ 1, 2 ; 3, 4 ]; j = 1 i = 1 if (M(i,j) > 2) %M(1,1) = 1 => Is 1 > 2? => False M(i,j) = 0; %This statement is not executed because the Because of the semicolons, nothing will be displayed. 
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 nestedfor
loops?  What does the
rand
function do?  What are the values of matrix
B
after the nestedfor
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.
Answer 

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

2.43. If Statement in loop
 What is
A
after the following is executed?  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
Answer  

clear; A = [1,2,3,4,5]; for i = [1:5] if (A(i) > 2) A(i) = 0; else A(i) = 1; end 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 any0
with a1
.
Answer 

for i = [1:5] if (A(i) == 0) A(i) = 1 end end 
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.
Answer 

for i = [1:5] if (A(i) == 0) A(i) = i end end 
2.45. while
loop
3. Activities
3.1. Introduction to Iteration
In this inclass 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 onebyone 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 longhand 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 longhand 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].