A bakery makes cakes, loaves of bread and batches of cookies. Each recipe needs flour, sugar, butter and eggs. Today's order is 2 cakes, 3 loaves and 4 batches of cookies. How much of each ingredient does the baker need? Put the recipes in a matrix and the order in a vector, multiply them, and out comes the shopping list. That's matrix-vector multiplication.
There are two ways to see what it does, and you need both. The row view says each answer is a dot product: one row of the matrix combined with the vector. The column view says the whole answer is a mix of the matrix's columns, with the vector saying how much of each. The row view is how you calculate; the column view is how you understand what a matrix does. Every prediction a linear model makes, X @ w, is this operation.
What you need first: what is a matrix?, the dot product explained and linear combinations from vector addition and scalar multiplication.
Key terms
- Matrix-vector product: a matrix A times a vector x, written Ax. The answer is a new vector.
- Row view: each entry of Ax is the dot product of one row of A with x.
- Column view: Ax is a linear combination of the columns of A, using the entries of x as the amounts.
- Linear map (or linear transformation): a rule that turns vectors into vectors in a way that respects adding and scaling. Every matrix is one.
- Bias (or intercept): a fixed number added to every prediction, the b in Xw + b.
The bakery's shopping list
Each column of the recipe matrix is one product, and each row is one ingredient:
import numpy as np
# cake bread cookies
recipes = np.array([
[250, 500, 300], # flour (g)
[200, 10, 150], # sugar (g)
[150, 20, 200], # butter (g)
[ 4, 0, 1], # eggs
])
order = np.array([2, 3, 4]) # 2 cakes, 3 loaves, 4 batches of cookies
needed = recipes @ order
print(needed)
[3200 1030 1160 12]
The baker needs 3,200 g of flour, 1,030 g of sugar, 1,160 g of butter and 12 eggs. @ is NumPy's sign for matrix multiplication. Here's the picture of both ways to get that answer:
The row view: one dot product per row
Take the flour row, (250, 500, 300): the grams of flour in one cake, one loaf and one batch of cookies. Combine it with the order (2, 3, 4) by multiplying matching numbers and adding:
250 × 2 + 500 × 3 + 300 × 4 = 500 + 1,500 + 1,200 = 3,200 g
That's the dot product of the flour row with the order. Each row gives one entry of the answer, so 4 rows give 4 numbers. Check it in code:
for ingredient, row in zip(["flour", "sugar", "butter", "eggs"], recipes):
print(ingredient, row @ order)
flour 3200
sugar 1030
butter 1160
eggs 12
The row view is how you calculate a matrix-vector product by hand, and how the computer does it.
The column view: a mix of the columns
Now read the same calculation by columns. The cake column, (250, 200, 150, 4), is the shopping list for one cake. Two cakes need twice that list. Three loaves need three times the bread column, and four batches need four times the cookies column. The full list is the sum:
cake, bread, cookies = recipes[:, 0], recipes[:, 1], recipes[:, 2]
print(2 * cake + 3 * bread + 4 * cookies)
[3200 1030 1160 12]
Same answer. This is a linear combination of the columns, and the order vector says how much of each column to take.
The column view is how you understand a matrix. It tells you that every answer Ax can ever give is some mix of the columns of A. A shopping list from this bakery is always some amount of the cake list plus some amount of the bread list plus some amount of the cookies list. Later in the course, this idea becomes "the column space", and it decides whether a system of equations has a solution.
The rule, as a summary of both views: for an m × n matrix A and a vector x with n entries,
(Ax)ᵢ = aᵢ₁x₁ + aᵢ₂x₂ + … + aᵢₙxₙ
Read it as "entry i of the answer is row i of A dotted with x".
The shape rule
The order vector has 3 entries because there are 3 products: one amount for each column. Predict what happens if you forget the cookies:
try:
recipes @ np.array([2, 3])
except ValueError as error:
print(str(error)[:70])
matmul: Input operand 1 has a mismatch in its core dimension 0, with g
The full message is long, but it means: the matrix has 3 columns and the vector has 2 entries, so they can't be paired up. The rule is:
| Matrix | Vector | Answer |
|---|---|---|
| m × n (here 4 × 3) | n entries (here 3) | m entries (here 4) |
The vector's length must equal the number of columns, and the answer has one entry per row. In words: one amount per product goes in, one total per ingredient comes out.
A matrix is a machine that turns vectors into vectors
Step back and look at what the recipe matrix does. It takes in a vector of 3 numbers (an order) and gives out a vector of 4 numbers (a shopping list). Every matrix is a machine like this: an m × n matrix turns vectors with n entries into vectors with m entries.
And it's a linear machine, in the sense of what is linear algebra?. Double the order and the shopping list doubles. Combine two orders and the shopping list is the sum of their two lists. Predict both results before you run this:
tomorrow = np.array([1, 5, 0])
print(recipes @ (2 * order), 2 * (recipes @ order))
print(recipes @ (order + tomorrow), recipes @ order + recipes @ tomorrow)
[6400 2060 2320 24] [6400 2060 2320 24]
[5950 1280 1410 16] [5950 1280 1410 16]
Each pair is identical. That's why the baker can plan each day's order separately and add the shopping lists at the end of the week.
With 2 × 2 matrices, the machine turns arrows on a flat page into other arrows: it can rotate them, stretch them or slant them. You'll watch that happen in the transformations module, which treats matrices as ways of moving space.
Where machine learning uses it: every prediction
A linear model, such as multiple linear regression, predicts a number by multiplying each feature by a weight, adding them up and adding a bias. For one flat with features (area in hundreds of square feet, bedrooms, age in years), that's a dot product. For a whole table of flats, it's a matrix-vector product:
X = np.array([
[9.5, 2, 10], # flat 1
[12.0, 3, 4], # flat 2
[6.5, 1, 20], # flat 3
])
w = np.array([6.0, 4.0, -0.5]) # lakh per 100 sq ft, per bedroom, per year of age
b = 10.0 # lakh
predictions = X @ w + b
print(predictions)
[70. 92. 43.]
Read it both ways:
- Row view: each flat's price is its features dotted with the weights, plus the bias. Flat 1: 9.5 × 6 + 2 × 4 + 10 × (−0.5) + 10 = 57 + 8 − 5 + 10 = 70 lakh.
- Column view: the predictions are 6 × the area column + 4 × the bedrooms column − 0.5 × the age column, plus 10. Each weight says how much its feature column contributes to every prediction at once.
The weights here are made up to keep the arithmetic clear. Training a model means finding the weights that make X @ w + b as close as possible to the real prices. Scikit-learn's LinearRegression.predict does exactly this calculation, and the bias is added by broadcasting.
Common mistakes
- Putting the vector on the wrong side.
recipes @ orderworks;order @ recipesneeds a vector with 4 entries, one per row, and means something different. Order matters. - Mixing up rows and columns in the setup. Here columns are products and rows are ingredients. Build it the other way round and the order vector has to match the other side. Say what rows and columns mean before multiplying.
- Using
*instead of@.recipes * ordermultiplies each row by the order entry by entry and returns a 4 × 3 matrix, not the shopping list. - Forgetting the bias.
X @ walone forces every prediction through zero when all features are zero.
Practice
- Work out [[1, 2], [3, 4]] times (5, 6) by hand, using the row view. Then check it with the column view.
Show the answer
Row view: (1 × 5 + 2 × 6, 3 × 5 + 4 × 6) = (17, 39). Column view: 5 × (1, 3) + 6 × (2, 4) = (5, 15) + (12, 24) = (17, 39).
print(np.array([[1, 2], [3, 4]]) @ np.array([5, 6]))
[17 39]
- What's
recipes @ np.array([0, 1, 0])? Explain the answer with the column view, without calculating.
Show the answer
It picks out the bread column: (500, 10, 20, 0), the shopping list for exactly one loaf. Multiplying by a vector with a single 1 selects one column.
- A matrix has shape
(5, 8). What length of vector can it multiply, and what's the length of the answer?
Show the answer
A vector with 8 entries, one per column. The answer has 5 entries, one per row.
- Predict the output of
recipes * orderand explain why it isn't the shopping list.
Show the answer
print(recipes * order)
[[ 500 1500 1200]
[ 400 30 600]
[ 300 60 800]
[ 8 0 4]]
Broadcasting multiplies each column by its amount but never adds across the row. Summing each row, (recipes * order).sum(axis=1), gives the shopping list.
- Change one weight in the flats example so that age doesn't affect the price at all. What do the predictions become?
Show the answer
Set the age weight to 0: w = np.array([6.0, 4.0, 0.0]). The predictions become 75, 94 and 53 lakh: each flat loses its age penalty.
- Using the column view, explain why the bakery's shopping list can never have sugar without flour, whatever the order.
Show the answer
Every shopping list is a mix of the three columns, with amounts that can't be negative (you can't bake −2 cakes). Every column that has sugar also has flour, so any mix with sugar has flour too. The column view tells you which answers are possible.
Interview questions
Explain matrix-vector multiplication in two ways.
For an m × n matrix A and a vector x of length n, Ax has length m. Row view: each entry is the dot product of a row of A with x. Column view: Ax is a linear combination of the columns of A, weighted by the entries of x. The column view shows that Ax always lies in the column space of A.
How does a linear regression model compute predictions for a dataset?
With the feature matrix X (n_samples × n_features), the weight vector w (n_features) and the bias b: predictions = Xw + b, a vector with one prediction per sample. Each prediction is the dot product of one row of X with w, plus b.
Key takeaways
- A matrix times a vector gives a new vector: an m × n matrix takes n numbers in and gives m numbers out.
- Row view: each entry of the answer is one row dotted with the vector. Use it to calculate.
- Column view: the answer is a mix of the columns, and the vector gives the amounts. Use it to understand what a matrix can produce.
- The vector's length must equal the number of columns.
- Every matrix is a linear machine, and every linear model's predictions are Xw + b.
Frequently asked questions
Why does the vector go on the right?
Convention: in Ax, the vector is treated as a column and pairs with the matrix's columns. Writing x on the left, as xA, treats it as a row and pairs it with the matrix's rows instead. NumPy allows both with 1D arrays, so be clear which one you mean.
Is matrix-vector multiplication the same as the dot product?
It's a set of dot products, one per row of the matrix. A dot product gives one number; a matrix-vector product gives a vector of them.
How do computers do this so fast?
Libraries such as NumPy call highly tuned code (often called BLAS) that processes many numbers per step and uses the CPU's cache well. GPUs go further by running thousands of multiply-and-adds at the same time, which is why they train neural networks so quickly.
What to learn next
- Multiply by many vectors at once in matrix multiplication explained.
- See Xw + b trained on real data in multiple linear regression.
- Revisit the building block in the dot product explained.