6.5: Nested Loops
- Page ID
- 84715
The next step is to write loops that enumerate different values of a
, b
, and c
. Create a new file called find_triples.m where we’ll develop the rest of the program.
We’ll start with a loop for a
:
for a=1:3
a
end
It might seem silly to start with such a simple program, but this is an essential element of incremental development: start simple and test as you go.
The output is as expected.
1
2
3
Now we’ll add a second loop for b
. It might be tempting to write something like this:
for a=1:3
disp(a)
end
for b=1:4
disp(b)
end
But that loops through the values of a
and then loops through the values of b
, and that’s not what we want.
Instead, we want to consider every possible pair of values, like this:
for a=1:3
for b=1:4
disp([a,b])
end
end
Now one loop is inside the other. The inner loop gets executed three times, once for each value of a
, so here’s what the output looks like (I’ve adjusted the spacing to make the structure clear):
>> find_triples
1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1
3 2
3 3
3 4
The left column shows the values of a
and the right column shows the values of b
.
The next step is to search for values of c
that might make a Pythagorean triple. The largest possible value for c
is a + b
, because otherwise we couldn’t form a triangle (see https://greenteapress.com/matlab/triangle).
for a=1:3
for b=1:4
for c=1:a+b
disp([a,b,c])
end
end
end
After each small change, run the program again and check the output.