Matrix Multiplication

Intuition

Each entry of a product ABAB is a dot product: row ii of AA with column jj of BB. A matrix can be seen as a machine that transforms vectors; multiplying matrices composes the machines.

Precise explanation

If AA is m×nm\times n and BB is n×pn\times p, then C=ABC = AB is m×pm\times p with

Cij=∑k=1nAikBkj.C_{ij} = \sum_{k=1}^{n} A_{ik} B_{kj}.

The inner dimensions must match (nn). The shapes "cancel" like dominoes: (m×n)(n×p)=m×p(m\times \mathbf{n})(\mathbf{n}\times p) = m\times p.

Properties: associative, (AB)C=A(BC)(AB)C = A(BC); distributive; not commutative — ABAB and BABA usually differ, and one may not even be defined. The identity matrix II satisfies AI=IA=AAI = IA = A.

Worked example

(1234)(5678)=(1⋅5+2⋅71⋅6+2⋅83⋅5+4⋅73⋅6+4⋅8)=(19224350).\begin{pmatrix}1&2\\3&4\end{pmatrix}\begin{pmatrix}5&6\\7&8\end{pmatrix} =\begin{pmatrix}1\cdot5+2\cdot7 & 1\cdot6+2\cdot8\\ 3\cdot5+4\cdot7 & 3\cdot6+4\cdot8\end{pmatrix} =\begin{pmatrix}19&22\\43&50\end{pmatrix}.

Reversing the order gives (23343146)\begin{pmatrix}23&34\\31&46\end{pmatrix} — 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 XWXW; a batch of predictions from linear regression is XwXw; attention is softmax(QK⊤)V\text{softmax}(QK^\top)V. Shape reasoning is the most useful debugging skill in ML.

References