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 and the product is defined entry by entry [1]:
Inner dimensions must match (3 = 3); the result takes the outer dimensions, 2×2.
1
2
3
4
5
6
7
8
9
10
11
12
0
0
0
0
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 C1 / 18
C is an 2×2 matrix of zeros.
- multiplications
- 0
Reading the animation
Row of and column of light up, and the highlighted pair is multiplied and added into . Once all terms are summed, the cell holds the dot product of row and column .
Cost
Every one of the output cells needs multiplications, for in total. That is for square matrices.
Pitfalls
- in general, and may not even be defined.
- The inner dimensions must match: .
References
- 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.