Indexing and the triple loop

A matrix is a flat strip of numbers. Multiplying two by hand in Python shows how indices map to memory — and what n³ loop iterations cost.

What you'll learn
  • Map a 2D index (i, j) to its position in row-major memory
  • Trace the i, j, k loop of a matrix product by hand
  • Explain why NumPy's m @ m is hundreds of times faster than the same loop in Python

The first structure in the repository is the simplest one there is: an array. indexing.py builds a 5×5 matrix of the numbers 0 to 24 and multiplies it by itself with three nested loops:

matrix = np.linspace(0, 24, 25).reshape(5, 5)
n = 5
mul = np.zeros((n, n))
for i in range(matrix.shape[0]):
    for j in range(matrix.shape[1]):
        for k in range(matrix.shape[1]):
            mul[i, j] += matrix[i, k] * matrix[k, j]

The innermost line is the definition of matrix multiplication, \(\text{mul}_{ij} = \sum_k m_{ik}\, m_{kj}\): entry \((i, j)\) is the dot product of row \(i\) with column \(j\). The script prints

[[ 150.  160.  170.  180.  190.]
 [ 400.  435.  470.  505.  540.]
 ...
 [1150. 1260. 1370. 1480. 1590.]]

which matches matrix @ matrix exactly.

The triple loop on indexing.py's own matrix. Row i (blue) and column j (green) meet at one orange pair per step, and mul[i, j] grows by their product. The strip at the bottom is the same matrix as it sits in memory.

Two dimensions, one strip

reshape(5, 5) does not move any numbers. Memory is one-dimensional, and NumPy stores the matrix row-major: row 0, then row 1, and so on. Element \((i, k)\) sits at flat position \(5i + k\). In the loop, m[i, k] walks along a row — consecutive addresses — while m[k, j] jumps by a whole row (5 elements) every step. On large matrices that second access pattern is the slow one, because each jump can land on a different cache line; reordering the loops to i, k, j makes both inner accesses walk sequentially and is a classic optimisation in C.

What the loop costs

The loop body runs \(n^3\) times: 125 here, a million for \(n = 100\). In Python each iteration is an interpreted operation on boxed numbers, while m @ m hands the whole product to compiled BLAS code. Timed on the machine that built this page:

The loop's cost grows as n³ (doubling n from 100 to 200 took it from 0.37 s to 3.1 s, about 8×), and NumPy pulls further ahead as n grows.

Try it yourself. Swap the two inner loops in indexing.py to the order i, k, j and confirm the result is unchanged. Then print matrix.strides and matrix.T.strides and relate them to the 5i + k rule. Finally, time np.einsum("ik,kj->ij", m, m) against m @ m for n = 200.

View source on GitHub →