Algorithm Search⌘K

Proofs: Naive matrix multiplication

These are the human proofs of Naive matrix multiplication, at full length.

The triple loop computes the matrix product full

This proof shows: correctness, termination.

Let RR be a ring, or more generally a semiring: a set with an associative addition that has a neutral element 00, and a multiplication. Commutativity of the multiplication is not used. Let AA be an n×mn \times m matrix and BB an m×pm \times p matrix over RR, with n,m,p≥0n, m, p \ge 0.

Claim. MATRIX-MULTIPLY(A,B)(A, B) stops, and it returns the n×pn \times p matrix CC with C[i][j]=∑k=0m−1A[i][k]B[k][j]C[i][j] = \sum_{k=0}^{m-1} A[i][k] B[k][j] for all 0≤i<n0 \le i < n and 0≤j<p0 \le j < p. The sum is taken in the order k=0,1,…,m−1k = 0, 1, \ldots, m-1, and it is 00 when m=0m = 0.

Termination. Each of the three loops of lines L2, L3 and L5 runs over a fixed finite range, and the body changes none of the loop variables. So line L6 runs exactly nmpnmp times and the procedure stops.

Step 1 (the inner loop). Fix ii and jj. We show that each time the test of line L5 runs with the value kk, this invariant holds:

(S) s=∑t=0k−1A[i][t] B[t][j]s = \sum_{t=0}^{k-1} A[i][t] \, B[t][j].

Initialization. Line L4 sets s=0s = 0 and the first test has k=0k = 0. The sum over the empty range is 00, so (S) holds.

Maintenance. Assume (S) holds for k<mk < m. Line L6 sets ss to ∑t=0k−1A[i][t]B[t][j]+A[i][k]B[k][j]=∑t=0kA[i][t]B[t][j]\sum_{t=0}^{k-1} A[i][t] B[t][j] + A[i][k] B[k][j] = \sum_{t=0}^{k} A[i][t] B[t][j], by associativity of addition. The next test has the value k+1k + 1, so (S) holds again.

Termination. The loop exits at the test with k=mk = m. By (S), s=∑t=0m−1A[i][t]B[t][j]s = \sum_{t=0}^{m-1} A[i][t] B[t][j], which is the claimed value of C[i][j]C[i][j].

Step 2 (the outer loops). Line L7 then writes this value into C[i][j]C[i][j]. Lines L2 and L3 run the body once for each pair (i,j)(i, j) with 0≤i<n0 \le i < n and 0≤j<p0 \le j < p, and line L7 for the pair (i,j)(i, j) is the only write to C[i][j]C[i][j]. The computation of the pair (i,j)(i, j) reads only AA and BB, which the procedure never writes, and CC is a new matrix that shares no memory with them. So no later step changes C[i][j]C[i][j], and after the loops each entry has its claimed value. Line L8 returns CC. ■\blacksquare

Remark (loop orders). In any of the six orders of the three loops, with CC set to 00 at the start and the update C[i][j]←C[i][j]+A[i][k]B[k][j]C[i][j] \leftarrow C[i][j] + A[i][k] B[k][j] as the body, the triples (i,j,k)(i, j, k) with fixed (i,j)(i, j) are visited in increasing order of kk in the orders ijkijk, jikjik, ikjikj, jkijki, kijkij and kjikji, since kk is either the inner loop or an outer loop. So the same argument, applied to each fixed (i,j)(i, j), shows that all six orders return the same matrix, even when addition is not commutative.

Back to Naive matrix multiplication