Search

Search papers and lessons

Matrix Multiplication

Level 2 · 9 min read

Matrix multiplication combines two matrices into one by taking dot products of rows and columns, and it is the same as doing one linear map after another.

On this page

  • Colour = topic mix
  • Linear algebra
  • Discrete math
  • Sign in to see your progress

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: ABAB and BABA 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 AA that rotates every point in the plane by 90 degrees, and a matrix BB that doubles every horizontal distance. Both are linear transformations. Apply BB first and then AA to a point. The combined effect is a single new transformation. The matrix that does this in one step is the product ABAB.

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 AA with a column of BB. 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

Definition: Matrix product

Let AA be an m×nm \times n matrix and BB an n×pn \times p matrix. Their product C=ABC = AB is the m×pm \times p matrix with entries

Cij=∑k=1nAik Bkj,i=1,…,m,j=1,…,p.C_{ij} = \sum_{k=1}^{n} A_{ik}\, B_{kj}, \qquad i = 1, \dots, m, \quad j = 1, \dots, p.

Here AikA_{ik} is the entry in row ii, column kk of AA, and BkjB_{kj} is the entry in row kk, column jj of BB. The index kk runs over the shared dimension, the number of columns of AA and rows of BB. It is summed away. The entry CijC_{ij} is the dot product of row ii of AA with column jj of BB, using the dot product of two vectors of the same length nn.

The shape rule follows directly. To form each dot product, row ii of AA and column jj of BB must have the same length. So the number of columns of AA must equal the number of rows of BB. The result takes its row count from AA and its column count from BB:

(m×n)⋅(n×p)=(m×p).(m \times n)\cdot(n \times p) = (m \times p).

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 x\mathbf{x} with nn entries can be treated as an n×1n \times 1 matrix. Then AxA\mathbf{x} is the special case p=1p = 1:

(Ax)i=∑k=1nAik xk.(A\mathbf{x})_i = \sum_{k=1}^{n} A_{ik}\, x_k.

This is the operation a neural network layer performs on one input. The output has one entry per row of AA.

Key properties

Matrix multiplication obeys most of the rules you know from ordinary numbers, with one important exception.

  • Associative: (AB)C=A(BC)(AB)C = A(BC). You can group the products however you like. This is why chains of transformations can be combined in any grouping.
  • Distributive: A(B+C)=AB+ACA(B + C) = AB + AC and (A+B)C=AC+BC(A + B)C = AC + BC, whenever the shapes allow the sums.
  • Identity: ImA=A=AInI_m A = A = A I_n for the identity matrices of the right sizes.
  • Not commutative: ABAB and BABA are generally different. They may not even have the same shape.
  • Transpose of a product: (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top, where the transpose M⊤M^\top 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

Example
Two 2 by 2 matrices, both orders

Let

A=(1234),B=(0110).A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}, \qquad B = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}.

Compute ABAB. Each entry is row ii of AA dotted with column jj of BB.

  1. C11C_{11}: row 1 of AA is (1,2)(1, 2), column 1 of BB is (0,1)(0, 1). So 1⋅0+2⋅1=21 \cdot 0 + 2 \cdot 1 = 2.
  2. C12C_{12}: row 1 of AA is (1,2)(1, 2), column 2 of BB is (1,0)(1, 0). So 1⋅1+2⋅0=11 \cdot 1 + 2 \cdot 0 = 1.
  3. C21C_{21}: row 2 of AA is (3,4)(3, 4), column 1 of BB is (0,1)(0, 1). So 3⋅0+4⋅1=43 \cdot 0 + 4 \cdot 1 = 4.
  4. C22C_{22}: row 2 of AA is (3,4)(3, 4), column 2 of BB is (1,0)(1, 0). So 3⋅1+4⋅0=33 \cdot 1 + 4 \cdot 0 = 3.

So AB=(2143)AB = \begin{pmatrix} 2 & 1 \\ 4 & 3 \end{pmatrix}. Multiplying on the right by BB swapped the two columns of AA.

Now compute BABA. The same procedure gives BA=(3412)BA = \begin{pmatrix} 3 & 4 \\ 1 & 2 \end{pmatrix}. Multiplying on the left by BB swapped the two rows instead. The two products differ, so the order matters.

Example
A dense layer on a batch of inputs

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 2×32 \times 3 matrix XX (one row per sample) and the weights as a 3×23 \times 2 matrix WW:

X=(12001−1),W=(10021−1).X = \begin{pmatrix} 1 & 2 & 0 \\ 0 & 1 & -1 \end{pmatrix}, \qquad W = \begin{pmatrix} 1 & 0 \\ 0 & 2 \\ 1 & -1 \end{pmatrix}.

The product Y=XWY = XW has shape (2×3)(3×2)=2×2(2 \times 3)(3 \times 2) = 2 \times 2. Its entries:

  1. Y11Y_{11}: row 1 of XX is (1,2,0)(1, 2, 0), column 1 of WW is (1,0,1)(1, 0, 1). So 1+0+0=11 + 0 + 0 = 1.
  2. Y12Y_{12}: row 1 of XX is (1,2,0)(1, 2, 0), column 2 of WW is (0,2,−1)(0, 2, -1). So 0+4+0=40 + 4 + 0 = 4.
  3. Y21Y_{21}: row 2 of XX is (0,1,−1)(0, 1, -1), column 1 of WW is (1,0,1)(1, 0, 1). So 0+0−1=−10 + 0 - 1 = -1.
  4. Y22Y_{22}: row 2 of XX is (0,1,−1)(0, 1, -1), column 2 of WW is (0,2,−1)(0, 2, -1). So 0+2+1=30 + 2 + 1 = 3.

So Y=(14−13)Y = \begin{pmatrix} 1 & 4 \\ -1 & 3 \end{pmatrix}. Row ii of YY holds the two outputs for sample ii. 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.

SituationWhat goes wrongBetter choice
Shapes do not line upError, or in a loose library, a silent transpose elsewhereCheck the shape rule before writing the product; print shapes while debugging
Expecting AB=BAAB = BAWrong answers after swapping the orderKeep the order from the composition; use the transpose rule when reversing
Mixing * and matrix productIn NumPy, * multiplies entry by entry, not as matricesUse @ or np.matmul for the matrix product
Very large matricesThe naive method costs about mnpmnp multiplications; 100×200100 \times 200 times 200×50200 \times 50 needs 1,000,0001{,}000{,}000Use optimised BLAS libraries and GPUs; use specialised algorithms only when they pay off
Long chains of productsRecomputing the same product many timesMultiply once and reuse the result, or factor the chain in a good order

The naive cost of mnpmnp 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 n×nn \times n matrices with fewer than n3n^3 operations for large nn. 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 ABAB to exist, what must be true about the shapes of AA and BB, and what shape is the result?Show answer

The number of columns of AA must equal the number of rows of BB. If AA is m×nm \times n and BB is n×pn \times p, the product ABAB is m×pm \times p. The inner dimension nn is summed over and disappears. The outer dimensions give the result.

QuestionCompute ABAB for A=(2013)A = \begin{pmatrix} 2 & 0 \\ 1 & 3 \end{pmatrix} and B=(142−1)B = \begin{pmatrix} 1 & 4 \\ 2 & -1 \end{pmatrix}.Show answer

Take each row of AA dotted with each column of BB.

  • Row 1 (2,0)(2, 0) with column 1 (1,2)(1, 2): 2+0=22 + 0 = 2.
  • Row 1 (2,0)(2, 0) with column 2 (4,−1)(4, -1): 8+0=88 + 0 = 8.
  • Row 2 (1,3)(1, 3) with column 1 (1,2)(1, 2): 1+6=71 + 6 = 7.
  • Row 2 (1,3)(1, 3) with column 2 (4,−1)(4, -1): 4−3=14 - 3 = 1.

So AB=(2871)AB = \begin{pmatrix} 2 & 8 \\ 7 & 1 \end{pmatrix}.

QuestionWhy is it reasonable that ABAB and BABA are usually different, even when both products exist?Show answer

A matrix represents a transformation. ABAB means apply BB first, then AA. BABA means apply AA first, then BB. 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 32×78432 \times 784 with one row per image. The weight matrix is 784×128784 \times 128, so the inner dimensions match. The output is 32×12832 \times 128, one row of 128 values per image. If the weight matrix were transposed to 128×784128 \times 784, the product with the 32×78432 \times 784 input would be undefined, because 784 does not equal 128. The shape check catches the mistake before any numbers are computed.

Sources