Module 3 · Beginner · Matrices

Matrix multiplication explained

Matrix multiplication as many matrix-vector products at once: the row-times-column rule, the shape rule, why order matters, and neural network layers.

By theprogrammers team · · 11 min read

The bakery from matrix-vector multiplication now plans three days at a time. Monday, Tuesday and Wednesday each have their own order. You could multiply the recipe matrix by each day's order separately, or put the three orders side by side as the columns of one matrix and multiply once. That second option is matrix multiplication: many matrix-vector products done together.

Then the baker asks a second question: what will each day cost at each of two suppliers? That's another multiplication, chained onto the first. Chaining is where matrix multiplication earns its place. A neural network is a long chain of exactly these multiplications, and a graphics card is a machine built to do them fast.

What you need first: matrix-vector multiplication explained and the dot product explained.

Key terms

  • Matrix product: AB, a new matrix whose columns are A times each column of B.
  • Row-times-column rule: the entry in row i, column j of AB is the dot product of row i of A with column j of B.
  • Inner dimensions: in an (m × n) times (n × p) product, the two *n*s. They must match.
  • Commutative: an operation where order doesn't matter, like 3 × 5 = 5 × 3. Matrix multiplication is not commutative.
  • Associative: an operation where grouping doesn't matter: (AB)C = A(BC). Matrix multiplication is associative.

Three days of orders at once

Here are the recipes again (rows are ingredients, columns are products), and three days of orders as the columns of a second matrix:

import numpy as np

recipes = np.array([
    [250, 500, 300],   # flour (g)
    [200,  10, 150],   # sugar (g)
    [150,  20, 200],   # butter (g)
    [  4,   0,   1],   # eggs
])
#                   Mon Tue Wed
orders = np.array([
    [2, 1, 3],   # cakes
    [3, 5, 2],   # loaves
    [4, 0, 6],   # batches of cookies
])

needed = recipes @ orders
print(needed)
[[3200 2750 3550]
 [1030  250 1520]
 [1160  250 1690]
 [  12    4   18]]

The answer has one column per day and one row per ingredient. Monday's column, (3200, 1030, 1160, 12), is exactly the shopping list from the matrix-vector lesson. That's the whole idea:

Column j of AB is A times column j of B.

Check it for Tuesday:

print(recipes @ orders[:, 1])
[2750  250  250    4]

So you already know how to multiply matrices. It's matrix-vector multiplication, repeated for every column of the second matrix, with the answers placed side by side.

The row-times-column rule

Zoom in on a single entry. Tuesday's flour, row 0 and column 1 of the answer, comes from the flour row of recipes and Tuesday's column of orders:

(250, 500, 300) · (1, 5, 0) = 250 + 2,500 + 0 = 2,750 g

That's the rule for every entry: row i of the first matrix, dotted with column j of the second. Here's the picture, with the shapes that make it possible:

A 4 by 3 recipes matrix with its flour row highlighted, times a 3 by 3 orders matrix with its Tuesday column highlighted, equals a 4 by 3 answer with the entry in the flour row and Tuesday column highlighted: 250 × 1 + 500 × 5 + 300 × 0 = 2750. Below, the shapes (4, 3) @ (3, 3) → (4, 3): the inner 3s must match, and the outer 4 and 3 give the shape of the answer.

The rule, as a summary: if C = AB, then cᵢⱼ = aᵢ₁b₁ⱼ + aᵢ₂b₂ⱼ + … + aᵢₙbₙⱼ.

Here it is written as loops, so you can see there's no magic. Never use this in real code (it's thousands of times slower than @), but run it once:

def matmul(A, B):
    rows, inner = A.shape
    inner_b, cols = B.shape
    assert inner == inner_b, "inner dimensions must match"
    C = np.zeros((rows, cols), dtype=A.dtype)
    for i in range(rows):
        for j in range(cols):
            C[i, j] = A[i, :] @ B[:, j]   # row i dotted with column j
    return C

print(np.array_equal(matmul(recipes, orders), recipes @ orders))
True

The shape rule: inner must match, outer survive

A (4 × 3) matrix times a (3 × 3) matrix gives a (4 × 3) matrix. In general:

(m × n) @ (n × p) → (m × p)

  • The inner numbers must match, because each row of the first matrix (length n) is dotted with each column of the second (length n).
  • The outer numbers give the shape of the answer: one row for each row of the first matrix, one column for each column of the second.

Writing shapes next to each other is the fastest way to check any matrix code. In the bakery, the shapes also carry meaning: (ingredients × products) @ (products × days) → (ingredients × days). The products cancel out, the way "per product" cancels when you multiply grams per product by products.

Chaining: what does each day cost?

Two suppliers sell the ingredients at different prices: rupees per gram of flour, sugar and butter, and rupees per egg. Rows are suppliers, columns are ingredients:

#                  flour sugar butter egg
prices = np.array([
    [0.05, 0.06, 0.55, 7.0],   # supplier A
    [0.04, 0.07, 0.50, 8.0],   # supplier B
])
cost = prices @ needed
print(cost.round(1))
[[ 943.8  318.  1324.2]
 [ 876.1  284.5 1237.4]]

Check the shapes first: (suppliers × ingredients) @ (ingredients × days) → (suppliers × days). Each entry is what one day costs at one supplier. Supplier B is cheaper every day, saving about ₹68 on Monday.

The whole calculation was prices @ (recipes @ orders). Now group it the other way, (prices @ recipes) @ orders. Predict whether the answer changes, and what prices @ recipes means on its own:

cost_per_product = prices @ recipes
print(cost_per_product.round(1))
print(np.allclose(cost_per_product @ orders, cost))
[[135.   36.6 141. ]
 [131.   30.7 130.5]]
True

The answer doesn't change: matrix multiplication is associative. And the middle step has its own meaning: prices @ recipes is (suppliers × products), the cost of one cake, one loaf and one batch of cookies at each supplier. A cake costs ₹135 to make with supplier A's ingredients. The baker can work this out once and reuse it for every week's orders.

Associativity is also why a chain of linear steps can be collapsed into one. Two matrices applied one after the other act like a single matrix, their product. Remember this: it's the reason neural networks need something extra between their layers.

Order matters

With numbers, 3 × 5 = 5 × 3. With matrices, swapping the order usually gives a different answer, and often no answer at all. orders @ recipes would pair each row of orders (3 days) with each column of recipes (4 ingredients), and the shapes (3 × 3) @ (4 × 3) don't fit. Even square matrices of the same size usually disagree:

A = np.array([[1, 2], [0, 1]])
B = np.array([[0, 1], [1, 0]])
print(A @ B)
print(B @ A)
[[2 1]
 [1 0]]
[[0 1]
 [1 2]]

AB and BA are different. Think of each matrix as an action: "put on socks, then shoes" isn't the same as "shoes, then socks". When you read ABx, the matrix nearest the vector acts first: B acts on x, then A acts on the result.

Where machine learning uses it: neural network layers

A neural network processes a batch of examples at once. Say 32 handwritten digits, each flattened to 784 pixel values, form a matrix of shape (32 × 784). A layer with 128 outputs stores its weights as a matrix of shape (784 × 128). One matrix multiplication computes all 128 outputs for all 32 examples:

rng = np.random.default_rng(0)
batch = rng.random((32, 784))           # 32 examples, 784 pixels each
W1 = rng.normal(0, 0.05, (784, 128))    # layer 1 weights
W2 = rng.normal(0, 0.05, (128, 10))     # layer 2 weights: 10 digit scores

hidden = batch @ W1
scores = hidden @ W2
print(hidden.shape, scores.shape)
(32, 128) (32, 10)

The shapes tell the story: (32 × 784) @ (784 × 128) → (32 × 128), then (32 × 128) @ (128 × 10) → (32 × 10), one score per digit for each example. The random numbers stand in for trained weights; only the shapes matter here.

Now use associativity. batch @ W1 @ W2 equals batch @ (W1 @ W2), and W1 @ W2 is a single (784 × 10) matrix. So two layers that only multiply can do nothing that one layer can't. That's why real networks apply a small non-linear step, such as setting negative numbers to zero, between layers. Without it, a hundred layers would collapse into one matrix. You'll build this in the deep learning module of the machine learning course.

How much work is it?

Each entry of an (m × n) @ (n × p) product needs n multiplications, and there are m × p entries, so the total is m × n × p multiplications. Two 1,000 × 1,000 matrices need a billion. That's why matrix multiplication is the single most optimised operation in computing, and why GPUs, which can do thousands of multiplications at the same time, transformed deep learning.

It also means the grouping you choose can matter for speed, even though it doesn't change the answer. Multiplying a long chain in a smart order can save most of the work.

Common mistakes

  • Checking the wrong numbers. It's the inner dimensions that must match: the columns of the first and the rows of the second.
  • Assuming AB = BA. Order matters. Keep your matrices in the order the meaning requires.
  • Using * for matrix multiplication. * multiplies matching entries. Use @.
  • Reading a chain left to right as actions. In ABx, B acts first.

Practice

  1. Multiply [[1, 2], [3, 4]] by [[5, 6], [7, 8]] by hand, using row-times-column.
Show the answer

Top-left: 1 × 5 + 2 × 7 = 19. Top-right: 1 × 6 + 2 × 8 = 22. Bottom-left: 3 × 5 + 4 × 7 = 43. Bottom-right: 3 × 6 + 4 × 8 = 50.

print(np.array([[1, 2], [3, 4]]) @ np.array([[5, 6], [7, 8]]))
[[19 22]
 [43 50]]
  1. Which of these products are allowed, and what shape is each answer? (2 × 3) @ (3 × 5); (3 × 5) @ (2 × 3); (5 × 1) @ (1 × 5); (1 × 5) @ (5 × 1).
Show the answer

(2 × 3) @ (3 × 5) → (2 × 5). (3 × 5) @ (2 × 3) isn't allowed: 5 ≠ 2. (5 × 1) @ (1 × 5) → (5 × 5). (1 × 5) @ (5 × 1) → (1 × 1), a single number: it's a dot product.

  1. In the bakery, what does row 1, column 2 of cost_per_product mean, and what's its value?
Show the answer

Row 1 is supplier B and column 2 is cookies: the cost of the ingredients for one batch of cookies from supplier B, ₹130.5.

  1. Predict, then check: what's orders @ np.array([1, 1, 1])? What does it mean?
Show the answer
print(orders @ np.array([1, 1, 1]))
[ 6 10 10]

Multiplying by a vector of ones adds up each row: the total cakes, loaves and batches over the three days.

  1. A layer takes inputs of shape (64 × 300) and must give outputs of shape (64 × 50). What shape is its weight matrix? How many weights is that?
Show the answer

(300 × 50), so that (64 × 300) @ (300 × 50) → (64 × 50). That's 15,000 weights.

  1. Explain in your own words why stacking two layers that only multiply by weight matrices gives no more power than one layer.
Show the answer

Because matrix multiplication is associative, X @ W1 @ W2 = X @ (W1 @ W2), and W1 @ W2 is a single matrix. Whatever the two layers do, one layer with that combined matrix does the same. A non-linear step between layers stops them collapsing.

Interview questions

When can two matrices be multiplied, and what is the shape of the result?

An m × n matrix can be multiplied by an n × p matrix: the number of columns of the first must equal the number of rows of the second. The result is m × p, and each entry is the dot product of a row of the first with a column of the second.

Is matrix multiplication commutative? Is it associative?

It's not commutative: AB is generally different from BA, and one may not even be defined. It is associative: (AB)C = A(BC), and it distributes over addition: A(B + C) = AB + AC.

Why do neural networks need non-linear activation functions?

Without them, each layer is a matrix multiplication (plus a bias), and a composition of such affine maps is itself a single affine map. A deep network would then be no more expressive than one linear layer. Non-linear activations such as ReLU let networks represent non-linear functions.

Key takeaways

  • Matrix multiplication is matrix-vector multiplication for every column of the second matrix: column j of AB is A times column j of B.
  • Each entry is a row of the first matrix dotted with a column of the second.
  • (m × n) @ (n × p) → (m × p): inner dimensions match, outer dimensions survive.
  • Order matters (AB ≠ BA), but grouping doesn't ((AB)C = A(BC)), so chains of linear steps collapse into one matrix.
  • Neural network layers are matrix multiplications on batches, with non-linear steps in between so the layers don't collapse.

Frequently asked questions

Why is matrix multiplication defined in this strange way?

Because it's exactly what chaining linear steps requires. If B turns orders into shopping lists and A turns shopping lists into costs, then AB must turn orders straight into costs, and the row-times-column rule is the only rule that makes that work.

What's the difference between np.dot, np.matmul and @?

For 1D and 2D arrays they give the same answers; @ is short for np.matmul and is the clearest to read. They differ for arrays with more than two dimensions, where @ treats the extra dimensions as a stack of matrices, which is what deep learning wants.

Can I multiply a matrix by itself?

Only if it's square: (n × n) @ (n × n). AA is written A², and repeated multiplication shows up in Markov chains and in how networks of links are analysed.

What to learn next

  1. Flip a matrix's rows and columns, and see why shapes sometimes need it, in the transpose of a matrix.
  2. Watch a matrix move arrows in the transformations module, coming next in this course.
  3. Revisit the single-column case in matrix-vector multiplication explained.