Foundations of computer programming in MATLAB — Loops
The idea of loops
Loops allow us to repeat the same snippet of code. Of course, we could just copy/paste it a bunch of times, but that has two major limitations:
- we have to hard-wire in the number of times to repeat it and
- it looks like đź’©.
And remember: if it looks like đź’©, it probably is đź’©.
The for loop
We consider first the for
loop, which repeats the same snippet of code a pre-determined number of times. The syntax is shown in the following “pseudocode.””
for INDEX = ARRAY
SNIPPET OF CODE
end
Here’s a specific example.
for i = 2:2:10
disp(['i equals ',num2str(i)])
end
The interpreter first assigns i = 2
, then executes the snippet, which prints 'i equals 2'
. Then it it assigns i = 4
, then it executes the snippet again, which prints 'i equals 4'
. Et cetera. The snippet will be executed length(2:2:10)
times.
This is wildly useful. Let’s actually do something in a for
loop.
v = zeros(9,1); % preallocate v
for i = 2:length(v)
v(i) = v(i-1) + 5;
end
disp(v)
Loops are not the most efficient choice for some tasks. When efficiency matters, we try to eliminate loops, especially for
loops, by using “vectorized” operations. For instance, we could have obtained the same v
from the loop above with the following code.
v = 0:5:40;
But sometimes we must compute something that is not so easily constructed otherwise. In these cases, we often just use it. Here’s one such example.
v_rand = randi(10,50,1); % vector of random integers between 1 and 10
for i = 1:length(v_rand)
if v_rand(i) > 5
disp('big')
else
disp('little')
end
end
In this loop, there was no simple substitute for going through each value of v_rand
and testing it.
Exercises
- Use a
for
loop to create a10
by1
array that has its first value equal to10
and each consecutive value thereafter equal to the square root of the previous. - Use a
for
loop to perform a simulation to estimate the probability of rolling a1
on a six-sided die on two consecutive rolls. How many trials did you need to get close to the true probability?
The while loop
The while
loop evaluates a conditional statement at the beginning of each loop to determine whether or not to evaluate the contained snippet. Here’s the pseudocode.
while CONDITION
SNIPPET OF CODE
end
If CONDITION
evaluates to 1
(true
), the snippet is evaluated. After the snippet is evaluated, CONDITION
is evaluated again to see if it is still true. Et cetera.
Here’s an example.
secret_number = randi(5);
not_yet_guessed = true;
while not_yet_guessed
guess = input('Guess an integer between 1 and 5: ');
if guess == secret_number
disp('you win!')
not_yet_guessed = false;
else
disp('Nope. Try again: ')
end
end
Notice that if we never guess correctly, we just keep repeating the loop! While loops can do that. It’s nice because we don’t have to know beforehand how many times we need to repeat the loop, but it can also be dangerous. What if you enter had made it an integer between 1
and 1e5
? You’d be guessing a while! Or, worse yet, you might make a while loop that never stops running. For instance, see the following example.
i_am_awesome = true;
while i_am_awesome
disp('Yes, so awesome.')
end
This loop never ends because it never changes the condition: i_am_awesome
is always true. If you happen to start running such a loop, you can exit it in the Command Window
by typing control+c
(Windows) or command+.
(OS X).
Exercise
Use a while
loop to test the probability of rolling snake eyes (two 1
s), again. This time, simulate until the estimate changes less than $1\ \%$ from the previous estimate.