Matrix Multiplication
Intuition
Each entry of a product is a dot product: row of with column of . A matrix can be seen as a machine that transforms vectors; multiplying matrices composes the machines.
Precise explanation
If is and is , then is with
The inner dimensions must match (). The shapes "cancel" like dominoes: .
Properties: associative, ; distributive; not commutative — and usually differ, and one may not even be defined. The identity matrix satisfies .
flowchart LR
A["A (m×n)"] --> C["C = AB (m×p)"]
B["B (n×p)"] --> C
C --> e["C[i][j] = row i of A · column j of B"]
Worked example
Reversing the order gives — different.
Common mistakes
- Multiplying element-wise (the Hadamard product) instead.
- Checking
len(A) == len(B)instead of columns of A vs rows of B. - Pre-allocating with
[[0]*p]*m(aliased rows — see PY-20).
Why this matters
A dense neural-network layer is ; a batch of predictions from linear regression is ; attention is . Shape reasoning is the most useful debugging skill in ML.
References
- Mathematics for Machine Learning — Marc Peter Deisenroth, A. Aldo Faisal, Cheng Soon Ong (Cambridge University Press) (
S009)