Matrix Addition
Two matrices of the same size are added entry by entry. This lesson defines matrix addition and subtraction, lists the algebraic laws they obey, and warns about NumPy broadcasting, which happily "adds" matrices of different sizes that mathematics would reject.
The definition
If and are both , their sum is the matrix
Each entry of the result is the sum of the entries in the same position:
If and have different sizes, is undefined. There is no sensible way to pair up the entries of a and a matrix.
The negative flips every sign, and subtraction is .
The laws of addition
Because each entry is just an ordinary sum of numbers, matrix addition inherits the laws of number addition. For of the same size and the zero matrix :
| Law | Statement |
|---|---|
| Commutative | |
| Associative | |
| Zero (additive identity) | |
| Negatives (additive inverse) | |
| Cancellation |
A one-line proof of the commutative law: the entry of is , the entry of is , and these numbers are equal. The same "look at one entry" argument proves every row of the table.
These laws mean you can solve matrix equations with addition exactly like number equations. From you get .
from sympy import Matrix, Rational, zeros
A = Matrix([[2, -1, 0], [7, 5, 1]])
B = Matrix([[3, 4, -6], [-2, 0, 9]])
C = Matrix([[Rational(1, 2), 0, 1], [0, Rational(-3, 4), 2]])
print("A + B =", (A + B).tolist())
print("A - B =", (A - B).tolist())
print("commutative:", A + B == B + A)
print("associative:", (A + B) + C == A + (B + C))
print("A + (-A) is zero:", A + (-A) == zeros(2, 3))
X = B - A # solves X + A = B
print("X =", X.tolist(), " check:", X + A == B)A + B = [[5, 3, -6], [5, 5, 10]]
A - B = [[-1, -5, 6], [9, 5, -8]]
commutative: True
associative: True
A + (-A) is zero: True
X = [[1, 5, -6], [-9, -5, 8]] check: True
Sizes must match (and NumPy broadcasting)
SymPy refuses to add matrices of different shapes, as the mathematics says it should. NumPy instead broadcasts: it stretches a row (or an column) across the other operand. That is extremely useful, but it is not matrix addition, and it can hide a shape bug.
import numpy as np
from sympy import Matrix
try:
Matrix([[1, 2], [3, 4]]) + Matrix([[1, 2, 3]])
except Exception as e:
print("SymPy:", type(e).__name__)
M = np.array([[1, 2, 3],
[4, 5, 6]])
row = np.array([10, 20, 30]) # shape (3,)
col = np.array([[100], [200]]) # shape (2, 1)
print(M + row) # row added to every row
print(M + col) # column added to every column
bad = np.array([[1], [2], [3]]) # (3, 1) + (3,) → (3, 3)!
print((bad + row).shape)SymPy: ShapeError
[[11 22 33]
[14 25 36]]
[[101 102 103]
[204 205 206]]
(3, 3)
The last line is the classic accident: a column vector plus a row vector gives a full matrix with no error at all. When shapes matter, assert them (assert a.shape == b.shape). The rules are covered in NumPy Broadcasting.
In software
- Neural networks: a dense layer computes . Here is a matrix and the bias is one row; adding to every row is broadcasting, exactly the
M + rowcase above (Neural Network Layers as Matrices). - Gradient accumulation: training loops add the gradient matrices of several mini-batches, , before one update step. That works because every gradient has the same shape as the weight matrix.
- Images: adding a constant brightens an image; adding two images of the same size overlays them (with clipping at the maximum pixel value in practice).
- Diffs and deltas: between two snapshots of a grid (a game map, a spreadsheet, a heat sensor) is the change matrix; its non-zero entries are what changed.
Exercises
Exercise 1: Add and subtract
Let and . Compute and ( doubles every entry).
Answer
; .
Solution
from sympy import Matrix
P = Matrix([[1, -3], [4, 0], [2, 2]])
Q = Matrix([[-1, 5], [6, -2], [0, 7]])
print((P + Q).tolist(), (2*P - Q).tolist())[[0, 2], [10, -2], [2, 9]] [[3, -11], [2, 2], [4, -3]]
Exercise 2: Solve for X
Solve for the matrix .
Answer
.
Solution
Subtract the known matrix from both sides: .
Exercise 3: Prove a law
Prove that for matrices of the same size.
Answer
Both sides have entry , so they are equal.
Solution
Both matrices are and agree in every entry, so they are equal.
Exercise 4: Catch the broadcast bug
Write a function safe_add(a, b) that adds two NumPy arrays only if their shapes are identical and raises ValueError otherwise. Test it on a (3, 1) and a (3,) array.
Answer
safe_add raises ValueError for shapes (3, 1) and (3,), and adds normally when shapes agree.
Solution
import numpy as np
def safe_add(a, b):
if a.shape != b.shape:
raise ValueError(f"shape mismatch {a.shape} vs {b.shape}")
return a + b
print(safe_add(np.ones((2, 2)), np.eye(2)).tolist())
try:
safe_add(np.ones((3, 1)), np.ones(3))
except ValueError as e:
print("ValueError:", e)[[2.0, 1.0], [1.0, 2.0]]
ValueError: shape mismatch (3, 1) vs (3,)
Test yourself
What is ?
- Undefined
When is defined?
- Always
- When has as many columns as has rows
- When and have exactly the same size
- Only for square matrices
In NumPy, what is the shape of a (4, 1) array plus a (4,) array?
- (4,)
- (4, 4)
- An error is raised
- (4, 1)