Skip to the workspace
Pebellslearn by building
Linear Algebra  ›  Lesson

Matrix Operations

Matrix & Matrix Operations 14 minMatrices add entry by entry, transpose by swapping rows and columns, and multiply only when the inner sizes match, giving a result shaped by the outer sizes.

machine learning / Matrix Operations

Explore each scene at your own pace.

01 · The rule

The rule

Matrix Operations

Dotting weights with one flat gives one prediction. The agency has thousands of flats, and a loop over them is slow and clumsy. One matrix multiplication predicts every rent at once, and nearly every "shape mismatch" error in ML code comes from not knowing when that multiplication is allowed.

The rule

Inner sizes must match; outer sizes give the answer's shape.

Take the flats as a matrix XX with 5 rows (flats) and 3 columns (size, rooms, metro km), and the weights as a column ww with 3 rows: [0.3, 1, -1].

  • Addition works entry by entry, so both matrices need the same shape.
  • Scalar multiplication multiplies every entry: 2X2X doubles every number.
  • Transpose swaps rows and columns: XTX^T is 3 × 5.
  • Matrix multiplication ABAB needs the columns of AA to equal the rows of BB. Each entry of the result is a row of AA dotted with a column of BB.

Writing shapes side by side, (5×3)(3×1)(5 \times 3)(3 \times 1): the inner 3s match, so XwXw exists, and the outer sizes give a 5 × 1 result, one prediction per flat.

import numpy as np
X = np.array([[40, 1, 2], [60, 2, 1], [80, 3, 3], [50, 2, 4], [70, 2, 1]])
w = np.array([0.3, 1, -1])
X @ w        # array([11., 19., 24., 13., 22.])

In NumPy, @ is matrix multiplication, while * multiplies entry by entry, stretching shapes where it can. So X * w runs without any error but returns a 5 × 3 table of products, not five predictions.

Order matters. ABAB and BABA are usually different, and often only one of them exists at all.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.