Module 3 · Beginner · Matrices

Matrix addition and scalar multiplication

Add, subtract and scale matrices entry by entry, with a sweet shop's weekly sales, a photo cross-fade, averaging model predictions and the weight update rule.

By theprogrammers team · · 11 min read

A sweet shop has three branches and sells three sweets. Each week's sales fit in a table: one row per branch, one column per sweet. To get the total for two weeks, you add the two tables entry by entry. To see what changed, you subtract them. To forecast 10% growth, you multiply every entry by 1.1. That's all there is to matrix addition and scalar multiplication: the same rules you used for vectors, applied to a whole table at once.

They're simple, but they're everywhere. A photo cross-fade, averaging two models' predictions and every step of training a neural network are built from exactly these two operations.

What you need first: what is a matrix? and vector addition and scalar multiplication.

Key terms

  • Matrix addition: adding two matrices of the same shape by adding the entries in matching positions.
  • Matrix subtraction: subtracting matching entries, again for matrices of the same shape.
  • Scalar multiplication: multiplying every entry of a matrix by the same number.
  • Linear combination of matrices: matrices scaled by numbers and added, such as 0.7A + 0.3B.
  • Broadcasting: NumPy's rule for combining arrays of different shapes, such as subtracting one row from every row of a matrix.

Adding two weeks of sales

Here are the boxes sold in two weeks. Rows are the branches (Jaipur, Pune, Kochi); columns are the sweets (laddoo, barfi, jalebi):

import numpy as np
import matplotlib.pyplot as plt

week1 = np.array([
    [40, 25, 30],   # Jaipur
    [35, 20, 45],   # Pune
    [20, 30, 15],   # Kochi
])
week2 = np.array([
    [45, 20, 35],
    [30, 25, 50],
    [25, 30, 10],
])
print(week1 + week2)
[[85 45 65]
 [65 45 95]
 [45 60 25]]

Each entry of the answer is the sum of the two entries in the same position. Jaipur sold 40 boxes of laddoo in week 1 and 45 in week 2, so the top-left entry is 85. No entry ever mixes with a different position: Jaipur's laddoo is only ever added to Jaipur's laddoo.

The rule, as a summary: if C = A + B, then cᵢⱼ = aᵢⱼ + bᵢⱼ for every row i and column j.

Subtraction shows what changed

print(week2 - week1)
[[ 5 -5  5]
 [-5  5  5]
 [ 5  0 -5]]

Positive entries grew, negative ones shrank. Kochi's jalebi sales fell by 5 boxes; its barfi stayed the same. A table of changes like this is often more useful to a manager than either table of totals.

Scaling every entry

Each box holds 12 sweets. How many sweets did each branch sell in week 1? Multiply every entry by 12:

print(12 * week1)
[[480 300 360]
 [420 240 540]
 [240 360 180]]

A forecast of 10% growth is a multiplication by 1.1. And the average of the two weeks is their sum multiplied by ½:

print(((week1 + week2) / 2))
[[42.5 22.5 32.5]
 [32.5 22.5 47.5]
 [22.5 30.  12.5]]

That last calculation, ½A + ½B, is a linear combination of two matrices: scale each one, then add. You met the same idea with vectors. In fact, matrix addition and scalar multiplication work exactly like they do for vectors, because a 3 × 3 matrix is just 9 numbers arranged in a grid. The grid only starts to matter when you multiply two matrices together, in matrix multiplication.

Shapes must match

What's the total if one table has a fourth branch? Predict what NumPy does before you run it:

week3 = np.array([
    [40, 25, 30],
    [35, 20, 45],
    [20, 30, 15],
    [10, 10, 10],   # a new branch in Kochi
])
try:
    week1 + week3
except ValueError as error:
    print(error)
operands could not be broadcast together with shapes (3,3) (4,3) 

There's no sensible answer: the new branch's row has nothing to be added to. Matrix addition needs the same shape, because every entry needs a partner. The error message talks about "broadcasting", NumPy's rule for when shapes are allowed to differ, which is next.

Broadcasting: one row added to every row

Sometimes you do want to combine a matrix with something smaller. The shop raises prices: laddoo by ₹20, barfi by ₹30, jalebi by ₹10 a box. Here are the old prices per box at each branch, and the increase applied to every branch at once:

old_prices = np.array([
    [300, 450, 200],
    [320, 460, 210],
    [280, 430, 190],
])
increase = np.array([20, 30, 10])
print(old_prices + increase)
[[320 480 210]
 [340 490 220]
 [300 460 200]]

increase has shape (3,) and old_prices has shape (3, 3). NumPy lines the vector up with the columns and adds it to every row, as if you had written it out three times. This is broadcasting. It isn't part of the maths of matrices: it's a NumPy convenience that saves you building the repeated matrix yourself.

It's also how data gets centred. Subtracting each column's average from every row is one broadcast, the first step of feature scaling and of PCA:

centred = week1 - week1.mean(axis=0)
print(centred.round(2))
print(centred.mean(axis=0).round(2))
[[  8.33   0.     0.  ]
 [  3.33  -5.    15.  ]
 [-11.67   5.   -15.  ]]
[-0.  0.  0.]

week1.mean(axis=0) is one average per sweet, shape (3,), and broadcasting subtracts it from each branch's row. Afterwards every column averages 0: each number now says how far a branch sits above or below the typical branch for that sweet. (The -0. is a tiny rounding leftover, about 0.000000000000001 below zero, that prints as zero with a minus sign.)

A cross-fade is a linear combination

A grayscale photo is a matrix of brightness values. So adding and scaling photos is matrix arithmetic, and you can watch it happen. A video cross-fade shows (1 − t) × first photo + t × second photo, with t sliding from 0 to 1. Before you run it, predict what the halfway frame (t = 0.5) looks like.

from sklearn.datasets import load_sample_images

photos = load_sample_images().images
pagoda = photos[0].mean(axis=2)    # colour to grayscale: average the 3 colour layers
flower = photos[1].mean(axis=2)
print(pagoda.shape, flower.shape)

fig, axes = plt.subplots(1, 4, figsize=(12, 2.6))
for ax, t in zip(axes, [0, 0.33, 0.67, 1]):
    blend = (1 - t) * pagoda + t * flower
    ax.imshow(blend, cmap="gray", vmin=0, vmax=255)
    ax.set_title(f"t = {t}")
    ax.axis("off")
plt.tight_layout()
plt.show()
(427, 640) (427, 640)
Four grayscale frames of a cross-fade. At t = 0 the frame is a pagoda by a lake; at t = 0.33 a flower appears faintly over the pagoda; at t = 0.67 the flower is stronger and the pagoda faint; at t = 1 only the flower remains.
  • load_sample_images ships with scikit-learn, so nothing is downloaded. It gives two colour photos of shape (427, 640, 3).
  • .mean(axis=2) averages the three colour layers, leaving one brightness matrix of shape (427, 640) per photo.
  • Both matrices have the same shape, so they can be scaled and added entry by entry: each pixel of the blend mixes the same pixel of both photos.

The halfway frame is both photos at half strength, laid over each other. Every frame is just a different linear combination of the same two matrices.

Where machine learning adds and scales matrices

Averaging two models' predictions

A classifier's predict_proba returns a matrix: one row per example, one column per class, each entry a probability. Averaging two models' matrices often predicts better than either model alone, because their mistakes partly cancel out. This is what scikit-learn's VotingClassifier(voting="soft") does:

model_a = np.array([[0.9, 0.1], [0.4, 0.6], [0.3, 0.7]])
model_b = np.array([[0.7, 0.3], [0.6, 0.4], [0.1, 0.9]])
average = (model_a + model_b) / 2
print(average)
print(average.argmax(axis=1))
[[0.8 0.2]
 [0.5 0.5]
 [0.2 0.8]]
[0 0 1]

argmax(axis=1) picks the column with the highest probability in each row: the predicted class. The two models disagreed about the second example, and the average sits on the fence at 0.5 each. When values tie, argmax picks the first, class 0.

The weight update

A neural network layer stores its weights in a matrix W. Training works out a matrix of gradients G of the same shape (which way each weight should move) and takes a small step:

W ← W − learning rate × G

That's a scalar multiplication followed by a subtraction, the same rule you met for vectors in gradient descent, applied to every weight in the matrix at once. A network with millions of weights does exactly this, millions of times.

Common mistakes

  • Adding matrices of different shapes. Every entry needs a partner in the same position. Check .shape on both.
  • Being surprised by broadcasting. NumPy may add a vector to every row without complaint. That's handy when you meant it and a silent bug when you didn't, so check the result's shape.
  • Confusing * with matrix multiplication. A * B multiplies matching entries, which is not the same as A @ B. See set up NumPy for linear algebra.
  • Overflowing small integer types. Photos are often stored as uint8, which only holds 0 to 255. Adding two such photos wraps round past 255 instead of giving 300. Convert to float first, as .mean() did above.

Practice

  1. Work out by hand: [[1, 2], [3, 4]] + [[10, 20], [30, 40]], and 3 × [[1, 0], [−2, 5]].
Show the answer

[[11, 22], [33, 44]] and [[3, 0], [−6, 15]].

print(np.array([[1, 2], [3, 4]]) + np.array([[10, 20], [30, 40]]))
print(3 * np.array([[1, 0], [-2, 5]]))
[[11 22]
 [33 44]]
[[ 3  0]
 [-6 15]]
  1. Is A + B always the same as B + A for matrices? Why?
Show the answer

Yes. Each entry is a sum of two ordinary numbers, and swapping the order of two numbers in a sum doesn't change it. (Matrix multiplication is different: there, order matters.)

  1. Predict the shape and values of week1 + np.array([[1], [2], [3]]). What did broadcasting do this time?
Show the answer
print(week1 + np.array([[1], [2], [3]]))
[[41 26 31]
 [37 22 47]
 [23 33 18]]

The column of shape (3, 1) lines up with the rows, so 1 is added across Jaipur's row, 2 across Pune's and 3 across Kochi's. Shape (3, 3).

  1. Write the cross-fade frame at t = 0.25 as a linear combination of the two photos. Which photo dominates?
Show the answer

0.75 × pagoda + 0.25 × flower. The pagoda dominates: it contributes three times as much brightness as the flower.

  1. Spot the bug: a student wants the change in sales per branch and writes (week2 - week1).sum(axis=0). What do they actually get?
Show the answer

axis=0 sums down the rows, removing the branches, so they get the change per sweet: [5, 0, 5]. For the change per branch they need axis=1, which gives [5, 5, 0].

  1. Why does averaging two models' probability matrices make sense, but averaging two models' predicted class labels (0 or 1) makes less sense?
Show the answer

Probabilities carry confidence: 0.9 and 0.6 average to a confident 0.75. Labels throw that away: averaging a 1 and a 0 gives 0.5, which says only that the models disagree, not which one was more sure.

Interview questions

What are the conditions for adding two matrices?

They must have the same shape: the same number of rows and the same number of columns. The sum is taken entry by entry. Libraries such as NumPy also allow broadcasting, which repeats a smaller array (such as a row vector) to match, but that's a library feature rather than standard matrix addition.

What does soft voting do in an ensemble?

Each model outputs a matrix of class probabilities (examples × classes). Soft voting averages these matrices, optionally with weights, and predicts the class with the highest averaged probability for each example. Hard voting instead takes a majority vote over predicted labels.

Key takeaways

  • Matrices of the same shape add and subtract entry by entry; scalar multiplication multiplies every entry by the same number.
  • These rules are the same as for vectors: a matrix behaves like its numbers laid out in a grid.
  • Linear combinations of matrices, such as ½A + ½B, give averages, cross-fades and forecasts.
  • Broadcasting lets NumPy add a row or column to every row or column; it centres data in one line, but check shapes to avoid silent bugs.
  • In machine learning, averaging probability matrices combines models, and W − learning rate × G trains every weight matrix.

Frequently asked questions

Is there matrix division?

Not entry by entry in linear algebra. "Dividing by a matrix" means multiplying by its inverse, which you'll meet in the transformations module of this course. NumPy's A / B divides matching entries, which is occasionally useful but isn't matrix algebra.

Does broadcasting exist in maths?

Not as such. In maths you'd write the repeated row out explicitly, or multiply by a column of ones. Broadcasting is a programming shortcut that does the same thing without building the bigger array.

Why is it called a scalar?

Because it scales: multiplying by 2 stretches every entry to twice its size. A scalar is a single number, as opposed to a vector or matrix.

What to learn next

  1. Combine a matrix with a vector in matrix-vector multiplication explained.
  2. Revisit centring and scaling in feature scaling.
  3. See the weight update in action in gradient descent explained.