11.4. Nested loops#
A loop can be contained of nested within another loop. The inner loop will be executed once per each iteration of the outer loop. The MATLAB syntax for nested loops will resemble the following.
for variable1 = list1
for variable2 = list2
% commands
end
end
For each value of variable1
from list1
the value of variable2
cycles through all of the values from list2
and the commands inside the inner loop are executed.
Nested loops can be particularly useful when dealing with 2D arrays. For example, lets generate a 10 \(\times\) 10 multiplication square (a 2D array where the value of each element is the product of the row and column numbers).
% Nested loops
multiplication_square = ones(10, 10);
for i = 1 : 10
for j = 1 : 10
multiplication_square(i, j) = i * j;
end
end
multiplication_square
Here we initialise M
to be a 10 \(\times\) 10 array of zeros and then use two nested for loops where the outer loop variable i
represents the row number and the inner loop variable j
represents the column number. Inside the inner loop we calculate the value of the row number multiplied by the column number and store that in the index (i, j)
.
Run your program and you will see the following added to the console output.
multiplication_square =
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
11.4.1. Exercise#
The matrix multiplication of an \(m \times p\) matrix \(A\) and a \(p \times n\) matrix \(B\) is defined by
For example,
Write a program that uses three nest for loops (one each for looping through values of \(i\), \(j\) and \(k\)) that computes the multiplication of two matrices. Use your program to calculate:
\(AB\)
\(BA\)
where