TExcelTAD
Home › Linear Algebra & Matrix Theory › Matrix Addition

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 A=[aij]A = [a_{ij}] and B=[bij]B = [b_{ij}] are both m×nm \times n, their sum is the m×nm \times n matrix

A+B=[aij+bij]A + B = [a_{ij} + b_{ij}]

Each entry of the result is the sum of the entries in the same position:

[2−10751]+[34−6−209]=[53−65510]\begin{bmatrix} 2 & -1 & 0 \\ 7 & 5 & 1 \end{bmatrix} + \begin{bmatrix} 3 & 4 & -6 \\ -2 & 0 & 9 \end{bmatrix} = \begin{bmatrix} 5 & 3 & -6 \\ 5 & 5 & 10 \end{bmatrix}

If AA and BB have different sizes, A+BA + B is undefined. There is no sensible way to pair up the entries of a 2×32 \times 3 and a 3×23 \times 2 matrix.

The negative −A=[−aij]-A = [-a_{ij}] flips every sign, and subtraction is A−B=A+(−B)=[aij−bij]A - B = A + (-B) = [a_{ij} - b_{ij}].

The laws of addition

Because each entry is just an ordinary sum of numbers, matrix addition inherits the laws of number addition. For A,B,CA, B, C of the same size m×nm \times n and the m×nm \times n zero matrix 00:

Law Statement
Commutative A+B=B+AA + B = B + A
Associative (A+B)+C=A+(B+C)(A + B) + C = A + (B + C)
Zero (additive identity) A+0=AA + 0 = A
Negatives (additive inverse) A+(−A)=0A + (-A) = 0
Cancellation A+C=B+C⇒A=BA + C = B + C \Rightarrow A = B

A one-line proof of the commutative law: the (i,j)(i, j) entry of A+BA + B is aij+bija_{ij} + b_{ij}, the (i,j)(i, j) entry of B+AB + A is bij+aijb_{ij} + a_{ij}, 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 X+A=BX + A = B you get X=B−AX = B - A.

python · try it yourself
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 1×n1 \times n row (or an m×1m \times 1 column) across the other operand. That is extremely useful, but it is not matrix addition, and it can hide a shape bug.

python · try it yourself
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 3×33 \times 3 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 XW+bXW + \mathbf{b}. Here XWXW is a (batch×units)(\text{batch} \times \text{units}) matrix and the bias b\mathbf{b} is one row; adding b\mathbf{b} to every row is broadcasting, exactly the M + row case above (Neural Network Layers as Matrices).
  • Gradient accumulation: training loops add the gradient matrices of several mini-batches, G=G1+G2+⋯G = G_1 + G_2 + \cdots, 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: B−AB - A 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 P=[1−34022]P = \begin{bmatrix} 1 & -3 \\ 4 & 0 \\ 2 & 2 \end{bmatrix} and Q=[−156−207]Q = \begin{bmatrix} -1 & 5 \\ 6 & -2 \\ 0 & 7 \end{bmatrix}. Compute P+QP + Q and 2P−Q2P - Q (2P2P doubles every entry).

Answer

P+Q=[0210−229]P + Q = \begin{bmatrix} 0 & 2 \\ 10 & -2 \\ 2 & 9 \end{bmatrix}; 2P−Q=[3−11224−3]2P - Q = \begin{bmatrix} 3 & -11 \\ 2 & 2 \\ 4 & -3 \end{bmatrix}.

Solution
P+Q:1+(−1)=0, −3+5=2 ∣ 4+6=10, 0+(−2)=−2 ∣ 2+0=2, 2+7=92P=[2−68044]2P−Q:2−(−1)=3, −6−5=−11 ∣ 8−6=2, 0−(−2)=2 ∣ 4−0=4, 4−7=−3\begin{aligned} P + Q&\text{:} \quad 1 + (-1) = 0,\ -3 + 5 = 2 \ \big|\ 4 + 6 = 10,\ 0 + (-2) = -2 \ \big|\ 2 + 0 = 2,\ 2 + 7 = 9 \\ 2P &= \begin{bmatrix} 2 & -6 \\ 8 & 0 \\ 4 & 4 \end{bmatrix} \\ 2P - Q&\text{:} \quad 2 - (-1) = 3,\ -6 - 5 = -11 \ \big|\ 8 - 6 = 2,\ 0 - (-2) = 2 \ \big|\ 4 - 0 = 4,\ 4 - 7 = -3 \end{aligned}
python · try it yourself
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 X+[210−4]=[55−13]X + \begin{bmatrix} 2 & 1 \\ 0 & -4 \end{bmatrix} = \begin{bmatrix} 5 & 5 \\ -1 & 3 \end{bmatrix} for the 2×22 \times 2 matrix XX.

Answer

X=[34−17]X = \begin{bmatrix} 3 & 4 \\ -1 & 7 \end{bmatrix}.

Solution

Subtract the known matrix from both sides: X=[5−25−1−1−03−(−4)]=[34−17]X = \begin{bmatrix} 5 - 2 & 5 - 1 \\ -1 - 0 & 3 - (-4) \end{bmatrix} = \begin{bmatrix} 3 & 4 \\ -1 & 7 \end{bmatrix}.

Exercise 3: Prove a law

Prove that (A+B)+C=A+(B+C)(A + B) + C = A + (B + C) for matrices of the same size.

Answer

Both sides have (i,j)(i, j) entry aij+bij+cija_{ij} + b_{ij} + c_{ij}, so they are equal.

Solution
((A+B)+C)ij=(aij+bij)+cijdefinition, twice=aij+(bij+cij)associativity of numbers=(A+(B+C))ijdefinition, twice\begin{aligned} ((A + B) + C)_{ij} &= (a_{ij} + b_{ij}) + c_{ij} && \text{definition, twice} \\ &= a_{ij} + (b_{ij} + c_{ij}) && \text{associativity of numbers} \\ &= (A + (B + C))_{ij} && \text{definition, twice} \end{aligned}

Both matrices are m×nm \times n 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
python · try it yourself
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 [1234]+[0−251]\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} + \begin{bmatrix} 0 & -2 \\ 5 & 1 \end{bmatrix}?

  1. Undefined
  2. [1485]\begin{bmatrix} 1 & 4 \\ 8 & 5 \end{bmatrix}
  3. [0−4154]\begin{bmatrix} 0 & -4 \\ 15 & 4 \end{bmatrix}
  4. [1085]\begin{bmatrix} 1 & 0 \\ 8 & 5 \end{bmatrix}

When is A+BA + B defined?

  1. Always
  2. When AA has as many columns as BB has rows
  3. When AA and BB have exactly the same size
  4. Only for square matrices

In NumPy, what is the shape of a (4, 1) array plus a (4,) array?

  1. (4,)
  2. (4, 4)
  3. An error is raised
  4. (4, 1)