ENع
←Matrix multiplication
Lesson 21 · Linear algebra and calculus

Matrix multiplication

14 min10 steps5 questionsAdvanced
About this lesson

Matrix multiplication is the workhorse of graphics and machine learning. Multiply a 2 × 3 matrix by a 3 × 2 matrix by hand and watch each entry of the answer appear as a dot product: a row of the first matrix paired with a column of the second, multiplied pair by pair and added up. Then see the shape rule, why the order matters, the triple loop in Python, what it costs, and NumPy's @ operator.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 21 · Interactive
01 / 10

Check the shapes first

A has 2 rows and 3 columns: it is 2 × 3. B is 3 × 2. You can multiply A by B only when A's columns match B's rows: 3 = 3. The result C takes A's rows and B's columns: 2 × 2.

>>> A = [[1, 2, 3], [4, 5, 6]]
>>> B = [[7, 8], [9, 10], [11, 12]]
>>> len(A), len(A[0]), len(B), len(B[0])
(2, 3, 3, 2)
Loading figure…
or ← →
Read the lesson step by step
  1. Check the shapes first

    A has 2 rows and 3 columns: it is 2 × 3. B is 3 × 2. You can multiply A by B only when A's columns match B's rows: 3 = 3. The result C takes A's rows and B's columns: 2 × 2.

    >>> A = [[1, 2, 3], [4, 5, 6]]
    >>> B = [[7, 8], [9, 10], [11, 12]]
    >>> len(A), len(A[0]), len(B), len(B[0])
    (2, 3, 3, 2)
  2. One entry: a dot product

    Each entry of C is a dot product. For row 1, column 1, pair row 1 of A with column 1 of B, multiply each pair and add: 1×7 + 2×9 + 3×11 = 7 + 18 + 33 = 58.

    >>> row, col = [1, 2, 3], [7, 9, 11]
    >>> [a * b for a, b in zip(row, col)]
    [7, 18, 33]
    >>> sum(a * b for a, b in zip(row, col))
    58
  3. Same row, next column

    Keep row 1 of A and move to column 2 of B: 1×8 + 2×10 + 3×12 = 8 + 20 + 36 = 64. The answer lands where that row and that column cross: row 1, column 2 of C.

    >>> sum(a * b for a, b in zip([1, 2, 3], [8, 10, 12]))
    64
  4. Row 2 fills the rest

    Row 2 of A works the same way. With column 1: 4×7 + 5×9 + 6×11 = 139. With column 2: 4×8 + 5×10 + 6×12 = 154. Four dot products, one per entry, fill C.

    >>> r2 = [4, 5, 6]
    >>> sum(a * b for a, b in zip(r2, [7, 9, 11])), sum(a * b for a, b in zip(r2, [8, 10, 12]))
    (139, 154)
  5. The rule in symbols

    In symbols, cᵢⱼ is the sum over k of aᵢₖ × bₖⱼ: row i of A slides along column j of B. If A is n × m and B is m × p, then C is n × p.

    >>> A = [[1, 2, 3], [4, 5, 6]]
    >>> B = [[7, 8], [9, 10], [11, 12]]
    >>> [[sum(A[i][k] * B[k][j] for k in range(3)) for j in range(2)] for i in range(2)]
    [[58, 64], [139, 154]]
  6. Columns: matrix times vector

    Read C by columns: column 1 of C is A times column 1 of B, a matrix times a vector. Graphics and machine learning do this constantly: a transform or a layer of weights times a column of numbers.

    >>> import numpy as np
    >>> A = np.array([[1, 2, 3], [4, 5, 6]])
    >>> A @ np.array([7, 9, 11])
    array([ 58, 139])
    >>> A @ np.array([8, 10, 12])
    array([ 64, 154])
  7. Order matters

    B times A is also allowed: B has 2 columns and A has 2 rows. But BA is 3 × 3, not 2 × 2. Even for square matrices, AB and BA are usually different, so never swap the order.

    >>> import numpy as np
    >>> A = np.array([[1, 2, 3], [4, 5, 6]])
    >>> B = np.array([[7, 8], [9, 10], [11, 12]])
    >>> (B @ A).shape
    (3, 3)
    >>> B @ A
    array([[ 39,  54,  69],
           [ 49,  68,  87],
           [ 59,  82, 105]])
  8. Three loops in Python

    In Python, three nested loops do it. i picks a row of A, j a column of B, and k walks along both, adding one product each time. Python counts from 0, so C[0][0] is c₁₁.

    >>> A = [[1, 2, 3], [4, 5, 6]]
    >>> B = [[7, 8], [9, 10], [11, 12]]
    >>> C = [[0, 0], [0, 0]]
    >>> for i in range(2):
    ...   for j in range(2):
    ...     for k in range(3):
    ...       C[i][j] += A[i][k]*B[k][j]
    ...
    >>> C
    [[58, 64], [139, 154]]
  9. Counting the work

    The innermost line runs once for every i, j and k: 2 × 2 × 3 = 12 multiplications. Two n × n matrices take n³, so doubling n makes the work 8 times bigger.

    >>> count = 0
    >>> for i in range(2):
    ...   for j in range(2):
    ...     for k in range(3):
    ...       count += 1
    ...
    >>> count
    12
    >>> 100**3, 200**3        # double n: 8 times the work
    (1000000, 8000000)
  10. NumPy does it with @

    Real code calls a library. NumPy's @ operator multiplies matrices: np.array(A) @ B gives [[58, 64], [139, 154]], the same C, and it runs the loops in fast compiled code.

    >>> import numpy as np
    >>> A = [[1, 2, 3], [4, 5, 6]]
    >>> B = [[7, 8], [9, 10], [11, 12]]
    >>> np.array(A) @ B
    array([[ 58,  64],
           [139, 154]])
    >>> (np.array(A) @ B).tolist()
    [[58, 64], [139, 154]]

Quiz Unlocks after the last step.