Matrices & matrix multiplication

Step 4 of 18 in Foundations · Build · Easy

A matrix is a transformation: multiplying by it rotates, stretches or projects vectors. Each output cell is a dot product of a row and a column, which is why inner dimensions must match.

The lesson

A matrix is a function on vectors. Multiply an m × n matrix A by a vector x of n numbers and you get m numbers; each one is the dot product of a row of A with x. The columns of A are where the unit vectors along each axis land.

The product AB means: apply B, then A. An (m × n) times an (n × p) gives an (m × p). The inner sizes must match because cell (i, j) of the result is row i of A dotted with column j of B, and a dot product needs equal lengths.

Worked example: A = [[1, 2], [3, 4]] times B = [[0, 1], [1, 0]]
  1. Top left: row [1, 2] · column [0, 1] = 2
  2. Top right: row [1, 2] · column [1, 0] = 1
  3. Bottom row: [3, 4]·[0, 1] = 4 and [3, 4]·[1, 0] = 3
  4. AB = [[2, 1], [4, 3]]. B swapped the columns of A.
A @ B    # matrix product
A * B    # element by element: a different operation

Common mistake. Order matters. AB and BA are usually different, and one of them may not even be defined. Rotating then shearing is not shearing then rotating.

Check yourself

  1. A is 2 × 3 and B is 3 × 4. What is the shape of A @ B?

    • 3 × 3
    • 2 × 4
    • It raises an error
    Show the answer

    2 × 4. The inner sizes (3 and 3) match and disappear. The outer sizes remain: 2 × 4.

  2. A = [[1, 2], [3, 4]] and x = [1, 1]. What is the second entry of A @ x?

    Show the answer

    7. Second row dotted with x: 3·1 + 4·1 = 7.

  3. A and B are both 2 × 3. Which of these works?

    • A @ B
    • Both
    • A @ B.T
    Show the answer

    A @ B.T. A @ B needs inner sizes 3 and 2 to match; they do not. B.T is 3 × 2, so A @ B.T is (2 × 3)(3 × 2) = 2 × 2.

Build it

  1. Triple-loop matmul

    matmul(A, B) with lists and three loops; raise ValueError on shape mismatch.

    Done when: Matches A @ B on random shapes; raises on (2×3)·(2×3).

    Runs in your browser: write the code on the map and the tests mark it.

  2. See a transformation

    Apply a 2×2 rotation and a shear matrix to a grid of points and plot before/after.

    Done when: Plot shows the grid rotated and sheared as expected.

Resources

Earn this star

On the map, your answers are marked and you log what you built. Finish the step and its star lights.

Open this step on the map