Matrix Multiplication Explained
Matrix Multiplication: The Strange Rule That Runs the World
Like my other notes, this is my own understanding written in plain words. For the full picture, watch a proper linear algebra course (3Blue1Brown's series is a great start). Think of this as a friendly map, not the textbook.
Matrix multiplication wasn't invented for neural networks. Neural networks inherited it from a mathematical idea that is centuries old, as I wrote in Matrix. Matrices represent transformations, and matrix multiplication represents applying or composing them. This whole note is me unpacking that one sentence.
First, what is a matrix?
A matrix is a grid of numbers with rows and columns. That is it. A spreadsheet is a matrix. A grayscale image is a matrix. A table of "how much of each ingredient in each recipe" is a matrix.
A vector is a matrix with a single column, like a point (x, y) or a list of features.
We say a matrix is
The rule everyone learns first
Here is the mechanical rule. To multiply
Let me finish the whole example so you can check yourself:
The top-left is
Will the shapes fit?
A row of
In code
def matmul(A, B):
m, n, p = len(A), len(B), len(B[0])
C = [[0] * p for _ in range(m)]
for i in range(m):
for j in range(p):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C
Three loops, and that is where the cost comes from (more on that later). In real life you never write this yourself:
import numpy as np
C = A @ B # the @ operator is matrix multiplication
But why this weird rule?
When I first saw this I asked: why not just multiply matching cells, like addition? That would be simpler. The answer took me a while to accept, and it is the most important part of this note.
A matrix is a machine that moves space
Think of a matrix as a function: you feed it a point, and it gives back a new point. It stretches, squishes, rotates or flips the whole plane.
The trick to reading a matrix is this: its columns tell you where the basic arrows
Take
Multiplying matrices means chaining the moves
Now suppose I rotate the plane, then stretch it. Two moves. I could apply them one after another to every point, or I could combine them into one matrix first and apply that once.
That combined matrix is exactly the product. And the strange row-times-column rule is not arbitrary. It is precisely the arithmetic you get when you ask: "if
Matrix multiplication looks odd because it is doing something deeper than arithmetic. It is function composition written as a table of numbers.
That is why order matters
Let
Different answers. Rotating then stretching is not the same as stretching then rotating, just like putting on socks then shoes is not the same as shoes then socks. So in general:
This is the biggest difference from ordinary number multiplication.
The rules of the game
| Property | True? | In plain words |
|---|---|---|
| No | Order matters | |
| Yes | Regroup freely, keep the order | |
| Yes | Distributes over addition | |
| Yes | The identity matrix |
|
| Yes | Transposing flips the order | |
| No | Two non-zero matrices can multiply to zero |
The associative rule is the secret to speed. If you must compute
Three ways to look at the same multiplication
Same answer, three mental pictures. Use whichever helps.
- Row times column: each cell is a dot product. Good for computing.
- Combination of columns:
is a mix of the columns of , with the entries of as amounts. Good for understanding transformations. - Sum of layers:
is a sum of (column of ) times (row of ) pieces. Good for understanding compression and low-rank ideas.
Why do we need it? Everywhere.
Here is the part that convinced me it is worth learning. The same operation keeps appearing in fields that seem unrelated.
1. Graphics and games
Every rotation, scaling, and camera move of a 3D model is a matrix. A game might chain a dozen moves. Instead of applying a dozen matrices to each of a million vertices, it multiplies the dozen into one matrix once and applies that. Your GPU does this billions of times a second.
2. Solving equations
Systems like
3. State machines and Markov chains
This one ties back to my note on State Machines Explained. A Markov chain is a state machine where transitions have probabilities, stored in a matrix
4. Graphs
Remember Graphs. Store a graph as an adjacency matrix (1 if two nodes are connected). Square it, and each cell counts the walks of length two between nodes. Cube it for length three. Path counting, without ever walking the graph.
5. Neural networks
A layer of a neural network takes some inputs and produces some outputs. Every input connects to every output with its own weight. Stack all those weights into a matrix
The magic is batching. Feeding 1000 examples at once is still a single multiply,
This is the connection to my state machine note too: an RNN's update
6. Attention in transformers
The engine of modern language models is built from matrix multiplies:
Turn each word into a row of numbers. Multiply the queries
Every cell of a product can be computed independently of the others. That is perfect for a chip with thousands of small cores. GPUs were built for graphics (which is matrix multiplies), and then AI turned out to want the same thing.
How expensive is it?
Multiplying two
- Strassen (1969) showed you can do better than
, roughly , by cleverly using fewer multiplications. - Researchers have pushed the theoretical exponent lower still, though those methods are rarely practical.
- In practice, speed comes from using the hardware well: block the matrices to fit in cache, use vector instructions, and run on GPUs and dedicated tensor cores.
For big matrices, the bottleneck is often not the arithmetic but moving numbers in and out of memory. Much of the craft of fast AI code is about that.
Why it keeps coming back
A matrix is a transformation. Matrix multiplication is doing one transformation after another, packaged as a single one. Rotate a model, walk a Markov chain, count paths in a graph, run a neural network layer, let words pay attention to each other: it is the same idea each time. The weird-looking row-times-column rule is simply the arithmetic of chaining moves.
Try it yourself
Related: Matrix, State Machines Explained, Graphs, Data Structures Explained