Matrices and matrix multiplication
Multiply matrices, read a matrix-vector product as a combination of columns, and know the rules that differ from ordinary numbers.
24 min
A matrix is a rectangular grid of numbers. An m × n matrix has m rows and n columns. The entry in row i, column j is aᵢⱼ.
- Add or subtract matrices of the same size, entry by entry. Scale by multiplying every entry.
- The transpose Aᵀ swaps rows and columns.
- The identity matrix I has 1s on the diagonal and 0s elsewhere; AI = IA = A.
You can multiply A (m × n) by B (n × p): the inner sizes must match, and the result is m × p. Entry (i, j) of AB is the dot product of row i of A with column j of B.
[1 2; 3 4] · [0 1; 1 0]: the first entry is 1·0 + 2·1 = 2, and the whole product is [2 1; 4 3].
For A = [a₁ a₂ …] with columns a₁, a₂, …, and a vector x = (x₁, x₂, …):
Ax = x₁a₁ + x₂a₂ + …
So Ax is a linear combination of the columns of A, and the system Ax = b asks: is b a combination of A's columns, and with which weights?
- AB ≠ BA in general. Order matters.
- (AB)C = A(BC): associative. A(B + C) = AB + AC.
- (AB)ᵀ = BᵀAᵀ: the order reverses.
- AB = 0 does not force A = 0 or B = 0.
Compute AB and BA for A = [1 2; 3 4] and B = [0 1; 1 0]. What does B do?
- 1
AB: row 1 · columns: (1·0 + 2·1, 1·1 + 2·0) = (2, 1); row 2: (3·0 + 4·1, 3·1 + 4·0) = (4, 3)
AB = [2 1; 4 3].
Compute A(2, 1) for A = [1 2; 3 4] as a combination of columns.
- 1
Columns: a₁ = (1, 3), a₂ = (2, 4)
Read the columns.
Write matmul(A, B) that returns the product of two matrices given as lists of rows. Assume the sizes match.
Your code must satisfy
- matmul([[1,2],[3,4]], [[0,1],[1,0]])→[[2,1],[4,3]]square
- matmul([[1,2,3],[4,5,6]], [[1,0],[0,1],[1,1]])→[[4,5],[10,11]]rectangular
- matmul([[7,8],[9,10]], [[1,0],[0,1]])→[[7,8],[9,10]]identity
def matmul(A, B):
# A is m x n, B is n x p; return an m x p list of lists
pass- AB is defined only when the inner sizes match; the result is (rows of A) × (columns of B).
- Entry (i, j) of AB is row i of A dotted with column j of B.
- Ax is a linear combination of the columns of A, weighted by x.
- Matrix multiplication is not commutative, and (AB)ᵀ = BᵀAᵀ.
- Ax = b asks whether b is in the span of A's columns.
Practice.
A is 2 × 3 and B is 3 × 4. The size of AB is:
- A2 × 4
- B3 × 3
- C2 × 3
- D4 × 2
A = [2 0; 1 3], B = [1 4; 2 1]. Find the entry in row 2, column 1 of AB.
Which is always true?
- AAB = BA
- B(AB)ᵀ = BᵀAᵀ
- CAB = 0 implies A = 0 or B = 0
- DA + B = B·A
A = [1 0; 0 2], x = (3, 5). The second component of Ax is:
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Linear Algebra is planned around your week. Free.