Sub topic 10
Matrix Multiplication
This chapter assumes you can write nested loops, index a list of lists with grid[r][c], and build a 2D list without shared rows. Here you will multiply two matrices by hand and in code, and learn what it costs.
The rule
To multiply matrix A (n by m) by matrix B (m by p), the number of columns in A must equal the number of rows in B. The result is an n by p matrix.
Each result cell result[i][j] is the dot product of row i of A and column j of B. A dot product multiplies matching entries and adds them up.
For A = [[1, 2], [3, 4]] and B = [[5, 6], [7, 8]], the top-left cell is 1*5 + 2*7 = 19.
| Cell | Row of A | Column of B | Calculation | Value |
|---|---|---|---|---|
| (0, 0) | 1, 2 | 5, 7 | 1·5 + 2·7 | 19 |
| (0, 1) | 1, 2 | 6, 8 | 1·6 + 2·8 | 22 |
| (1, 0) | 3, 4 | 5, 7 | 3·5 + 4·7 | 43 |
| (1, 1) | 3, 4 | 6, 8 | 3·6 + 4·8 | 50 |
The three-loop implementation
Two loops visit every result cell. A third loop runs along the shared dimension m to build the dot product.
def matmul(a, b):
n, m, p = len(a), len(b), len(b[0])
if len(a[0]) != m:
raise ValueError("inner dimensions must match")
result = [[0] * p for _ in range(n)]
for i in range(n):
for j in range(p):
for k in range(m):
result[i][j] += a[i][k] * b[k][j]
return result
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
print(matmul(A, B)) # [[19, 22], [43, 50]]Three details matter here:
- The dimension check runs first, so a mismatch fails with a clear message instead of an
IndexErrorpartway through. - The result is built with a comprehension, so each row is a separate list. Writing
[[0] * p] * nwould make every row the same list, and every update would show up in all rows. - In
a[i][k] * b[k][j],kwalks across a row ofAand down a column ofB.
Common errors
Matrix multiplication is not commutative. In general A × B and B × A differ, and one of them may not exist at all. A 2 by 3 matrix times a 3 by 4 matrix works. Reversed, the inner sizes are 4 and 2, so it fails.
Another frequent mistake is using the wrong bound for a loop. The k loop runs to m, the columns of A and rows of B. It does not run to n or p. Square matrices hide this mistake, so test with a non-square pair.
A = [[1, 2, 3], [4, 5, 6]] # 2 by 3
B = [[1, 0], [0, 1], [1, 1]] # 3 by 2
print(matmul(A, B)) # [[4, 5], [10, 11]]Cost
The loops run n * p * m times, and each pass does one multiplication and one addition. For two square n by n matrices, that is O(n³) time. Doubling n makes the work eight times larger. The result needs O(n·p) extra space, which is O(n²) for square matrices.
Faster algorithms exist, but the three-loop version is the standard baseline. For large numeric data, use a library such as NumPy, which runs the same operation in optimized compiled code.
Exercise
Matrix A is 4 by 2 and matrix B is 2 by 5. Can you compute A × B? If so, what is its shape and how many multiplications does the three-loop version perform?
Show answer
Yes. The inner dimensions match (both 2), so the result is 4 by 5. The loops perform n p m = 4 5 2 = 40 multiplications.
Exercise
Why does matmul build result with [[0] * p for _ in range(n)] instead of [[0] * p] * n?
Show answer
The second form repeats a reference to one inner list, so all n rows are the same list. Adding to result[i][j] would change that cell in every row. The comprehension creates a separate list for each row.