TL;DR
Multiplying two matrices gives you a third matrix. Each entry of the result is the dot product of one row of the first matrix with one column of the second. The rule looks arbitrary at first, but it is exactly what you get when you apply one transformation after another.
Matrix multiplication only works when the inner sizes agree, and the order matters: and are usually different.
Where you'll see it: in every layer of a neural network, which multiplies its inputs by a weight matrix, in the chaining of rotations and scalings in graphics, and in the update rules of linear regression.
Intuition
Doing two things in a row
Take a Matrix that rotates every point in the plane by 90 degrees, and a matrix that doubles every horizontal distance. Both are linear transformations. Apply first and then to a point. The combined effect is a single new transformation. The matrix that does this in one step is the product .
That is why the rule looks the way it does. Writing down the result of "rotate after stretch" for each basis direction forces you to take a dot product of a row of with a column of . The formula is not a convention someone chose for convenience. It is the only rule that makes the product of matrices match the composition of the maps they represent.
A second picture helps. Think of a matrix as a machine that takes in a list of numbers and returns a new list. Multiplying two matrices is wiring the output of the first machine into the input of the second. The result is one machine that does both jobs.
flowchart LR X[Input vector] --> B[Matrix B: stretch] B --> A[Matrix A: rotate] A --> Y[Output vector] B -. combined .-> AB[Matrix AB: stretch then rotate] AB -. same output .-> Y
Multiplication also shows up everywhere data is stored as a table. If the rows of one table are samples and the columns are features, multiplying that table by a weight matrix computes, for every sample at once, a weighted sum of its features. One operation handles the whole batch.
The math
Definition
Let be an matrix and an matrix. Their product is the matrix with entries
Here is the entry in row , column of , and is the entry in row , column of . The index runs over the shared dimension, the number of columns of and rows of . It is summed away. The entry is the dot product of row of with column of , using the dot product of two vectors of the same length .
The shape rule follows directly. To form each dot product, row of and column of must have the same length. So the number of columns of must equal the number of rows of . The result takes its row count from and its column count from :
Whenever the inner numbers do not match, the product is undefined. Code that multiplies arrays with the wrong shapes fails for exactly this reason.
A matrix times a vector
A vector with entries can be treated as an matrix. Then is the special case :
This is the operation a neural network layer performs on one input. The output has one entry per row of .
Key properties
Matrix multiplication obeys most of the rules you know from ordinary numbers, with one important exception.
- Associative: . You can group the products however you like. This is why chains of transformations can be combined in any grouping.
- Distributive: and , whenever the shapes allow the sums.
- Identity: for the identity matrices of the right sizes.
- Not commutative: and are generally different. They may not even have the same shape.
- Transpose of a product: , where the transpose flips a matrix over its diagonal so rows become columns. The order reverses.
The lack of commutativity is not a flaw. Rotating then stretching is not the same as stretching then rotating, so the matrices that represent those actions must not commute either.
Worked examples
Let
Compute . Each entry is row of dotted with column of .
- : row 1 of is , column 1 of is . So .
- : row 1 of is , column 2 of is . So .
- : row 2 of is , column 1 of is . So .
- : row 2 of is , column 2 of is . So .
So . Multiplying on the right by swapped the two columns of .
Now compute . The same procedure gives . Multiplying on the left by swapped the two rows instead. The two products differ, so the order matters.
A neural network layer takes a batch of inputs and maps each one to a set of outputs. Suppose there are 2 samples, each with 3 features, and the layer produces 2 outputs per sample. Write the inputs as a matrix (one row per sample) and the weights as a matrix :
The product has shape . Its entries:
- : row 1 of is , column 1 of is . So .
- : row 1 of is , column 2 of is . So .
- : row 2 of is , column 1 of is . So .
- : row 2 of is , column 2 of is . So .
So . Row of holds the two outputs for sample . The whole batch went through the layer in one multiplication, and the output shape came from the batch size and the number of outputs.
Tradeoffs and failure modes
Matrix multiplication is the workhorse of numerical computing, and it has a few traps.
| Situation | What goes wrong | Better choice |
|---|---|---|
| Shapes do not line up | Error, or in a loose library, a silent transpose elsewhere | Check the shape rule before writing the product; print shapes while debugging |
| Expecting | Wrong answers after swapping the order | Keep the order from the composition; use the transpose rule when reversing |
Mixing * and matrix product | In NumPy, * multiplies entry by entry, not as matrices | Use @ or np.matmul for the matrix product |
| Very large matrices | The naive method costs about multiplications; times needs | Use optimised BLAS libraries and GPUs; use specialised algorithms only when they pay off |
| Long chains of products | Recomputing the same product many times | Multiply once and reuse the result, or factor the chain in a good order |
The naive cost of multiplications matters a great deal in practice. Doubling each dimension multiplies the work by eight. Faster algorithms exist. Strassen's method, published in 1969, multiplies two matrices with fewer than operations for large . In practice, libraries use a mix of blocked algorithms and hardware-specific kernels, because the memory access pattern often matters more than the raw operation count.
History
Matrices were studied before they were given their modern notation. In the 1850s Arthur Cayley developed the algebra of matrices, and in his 1858 memoir he defined the product as composition of linear maps. That definition is the one used today. Earlier, James Joseph Sylvester had coined the word "matrix" for the rectangular arrays themselves.
Strassen's 1969 result showed that the obvious algorithm was not the fastest possible. It did not replace the definition, but it started a long line of research into how quickly two matrices can be multiplied. That research continues, and the best known exponents are still a topic of active study. For everyday use, the definition from Cayley's era remains the standard.
Check yourself
QuestionFor the product to exist, what must be true about the shapes of and , and what shape is the result?Show answer
The number of columns of must equal the number of rows of . If is and is , the product is . The inner dimension is summed over and disappears. The outer dimensions give the result.
QuestionCompute for and .Show answer
Take each row of dotted with each column of .
- Row 1 with column 1 : .
- Row 1 with column 2 : .
- Row 2 with column 1 : .
- Row 2 with column 2 : .
So .
QuestionWhy is it reasonable that and are usually different, even when both products exist?Show answer
A matrix represents a transformation. means apply first, then . means apply first, then . Those are different sequences of actions, so they generally have different effects. A rotation followed by a horizontal stretch does not place points where the stretch followed by the rotation does. Since the matrices encode these actions, their products inherit the difference.
QuestionA batch of 32 images, each flattened to 784 pixel values, goes through a dense layer with 128 outputs. What shapes do the input, the weight matrix and the output have, and what goes wrong if the weight matrix is transposed?Show answer
The input is with one row per image. The weight matrix is , so the inner dimensions match. The output is , one row of 128 values per image. If the weight matrix were transposed to , the product with the input would be undefined, because 784 does not equal 128. The shape check catches the mistake before any numbers are computed.