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#

Exercise 11.8

The matrix multiplication of an \(m \times p\) matrix \(A\) and a \(p \times n\) matrix \(B\) is defined by

\[ [AB]_{ij} = \sum_{k = 1}^p a_{ik}b_{kj}. \]

For example,

\[\begin{split} \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} \begin{pmatrix} 5 & 6 \\ 7 & 8 \end{pmatrix} = \begin{pmatrix} 5 + 14 & 6 + 16 \\ 15 + 28 & 18 + 32 \end{pmatrix} = \begin{pmatrix} 19 & 22 \\ 43 & 50 \end{pmatrix}.\end{split}\]

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:

  1. \(AB\)

  2. \(BA\)

where

\[\begin{split} \begin{align*} A &= \begin{pmatrix} 3 & 2 & -1 & 4 \\ 7 & -4 & 0 & 2 \end{pmatrix}, & B &= \begin{pmatrix} 1 & 0 \\ 3 & -2 \\ 3 & 6 \\ -1 & 4 \end{pmatrix}. \end{align*} \end{split}\]