/utils

Matrix Multiplication

See how each entry of a matrix product is the dot product of a row and a column, computed one multiplication at a time.

best
O(n^3)
average
O(n^3)
worst
O(n^3)
space
O(n^2)

For A∈Rn×mA \in \mathbb{R}^{n \times m} and B∈Rm×pB \in \mathbb{R}^{m \times p} the product C=AB∈Rn×pC = AB \in \mathbb{R}^{n \times p} is defined entry by entry [1]:

Cij=∑k=1mAik Bkj.C_{ij} = \sum_{k=1}^{m} A_{ik}\, B_{kj}.

Inner dimensions must match (3 = 3); the result takes the outer dimensions, 2×2.

1
2
3
4
5
6
A
·
7
8
9
10
11
12
B
=
0
0
0
0
C
1import numpy as np2 3 4def matmul(A, B):5    n, m = A.shape6    p = B.shape[1]7    C = np.zeros((n, p))8    for i in range(n):9        for j in range(p):10            # dot product of row i and column j11            for k in range(m):12                C[i, j] += A[i, k] * B[k, j]13    return C
1 / 18

C is an 2×2 matrix of zeros.

multiplications
0

Reading the animation

Row ii of AA and column jj of BB light up, and the highlighted pair Aik,BkjA_{ik}, B_{kj} is multiplied and added into CijC_{ij}. Once all mm terms are summed, the cell holds the dot product of row ii and column jj.

Cost

Every one of the n⋅pn \cdot p output cells needs mm multiplications, for n⋅m⋅pn \cdot m \cdot p in total. That is O(n3)O(n^3) for square matrices.

Pitfalls

  • AB≠BAAB \ne BA in general, and BABA may not even be defined.
  • The inner dimensions must match: (n×m)(m×p)(n \times m)(m \times p).

References

  1. G. Strang, Introduction to Linear Algebra, 5th ed., Wellesley-Cambridge Press, 2016.

Further reading

  • G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed., Johns Hopkins University Press, 2013.

Full bibliography