4.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 Python syntax for nested loops will resemble the following.

for variable1 in list1:
    for variable2 in list2:
        commands to be executed

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
import numpy as np

mult_square = np.ones((10, 10))

for i in range(10):
    for j in range(10):
        mult_square[i, j] = (i + 1) * (j + 1);
       
print()
print(mult_square)

Here we initialise mult_square 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]. Note that we need to add 1 to i and j due to zero indexing.

Run your program and you will see the following added to the console output.

[[  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.]]

4.4.1. Exercise#

Exercise 4.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. Given the matrices

\[\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}\]

use your program to calculate:

  1. \(AB\)

  2. \(BA\)