Matrix subtraction subtracts matching cells: C[i][j] = A[i][j] - B[i][j]. Both matrices must have the same number of rows and columns.
Remember
A − B is defined only when A and B have the same shape
[ 9 8 ] [ 1 5 ] [ 8 3 ]
[ 7 6 ] − [ 4 2 ] = [ 3 4 ]
Rule: (A − B)[i][j] = A[i][j] − B[i][j]
Negatives are allowed (e.g. 2 − 5 = −3).
Position
A
B
A − B
[0][0]
9
1
8
[0][1]
8
5
3
[1][0]
7
4
3
[1][1]
6
2
4
Approach
How to Subtract Matrices in Python
Four clear steps — same nested loops as addition, with minus.
Confirm both matrices have the same rows and columns.
Create a result matrix of that same size.
Outer loop walks rows; inner loop walks columns.
Set result[i][j] = A[i][j] - B[i][j] for every cell.
Method
Idea
Time
Best for
Nested loops
Subtract matching cells into a new matrix
O(m × n)
Interviews, teaching
Shape-safe subtract
Validate dimensions first, then subtract
O(m × n)
Safer production-style code
Pseudocode
Pseudocode
function SubtractMatrices(A, B):
rows = rows of A
cols = cols of A
if rows != rows of B or cols != cols of B:
error "shapes must match"
C = new matrix[rows][cols]
for i from 0 to rows - 1:
for j from 0 to cols - 1:
C[i][j] = A[i][j] - B[i][j]
return C
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Rule
C[i][j] = A[i][j] - B[i][j]
Requirement
Same rows and same columns
Storage
List of lists, e.g. [[9, 8], [7, 6]]
Negatives
Allowed and expected when B > A
Vs multiply
Subtraction is entrywise only
Classic check
[[9,8],[7,6]] − [[1,5],[4,2]] = [[8,3],[3,4]]
Try it
Live Preview
Pick a sample pair to see matrices A, B, and A − B.
Tap a chip to run. Results may include negative numbers.
Result
A =
9 8
7 6
B =
1 5
4 2
A − B =
8 3
3 4
Trace
Worked Walkthrough — 2×2
Visit every index once and subtract the matching cells.
Start with a clear nested-loop subtractor. Then add a shape check so mismatched sizes fail safely.
Example 1 — Nested Loops
Subtract two same-sized matrices cell by cell and print the result.
python
def subtract_matrices(a, b):
rows = len(a)
cols = len(a[0])
result = [[0] * cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
result[i][j] = a[i][j] - b[i][j]
return result
def print_matrix(m):
for row in m:
print(" ".join(str(val) for val in row))
a = [[9, 8], [7, 6]]
b = [[1, 5], [4, 2]]
print_matrix(subtract_matrices(a, b))
Output
8 3
3 4
How It Works
Read rows with len(a) and columns with len(a[0]).
Allocate a result matrix of the same size.
Outer loop chooses row i; inner loop chooses column j.
Store a[i][j] - b[i][j] into result[i][j].
Print walks the result the same way — one row per line.
Example 2 — Shape-Safe Subtract
Validate dimensions before subtracting so mismatched matrices fail with a clear error.
python
def subtract_matrices(a, b):
rows = len(a)
cols = len(a[0])
if len(b) != rows or any(len(row) != cols for row in a + b):
raise ValueError("Matrices must have the same dimensions.")
result = [[0] * cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
result[i][j] = a[i][j] - b[i][j]
return result
a = [[10, 9, 8], [7, 6, 5]]
b = [[1, 2, 3], [4, 5, 6]]
diff = subtract_matrices(a, b)
for row in diff:
print(" ".join(str(val) for val in row))
Output
9 7 5
3 1 -1
How It Works
Compare row counts and every row length before subtracting.
Raise ValueError if shapes differ — subtraction would be undefined.
Otherwise run the same nested-loop subtraction as Example 1.
For the 2×3 sample: 5 - 6 = -1 shows negatives are fine.
Mention the shape check in interviews even when samples already match.
Edge Cases & Pitfalls
Check these before calling the solution done.
Shape
Must match
Different sizes cannot be subtracted — validate first.
Negatives
Expected
When B[i][j] > A[i][j], the cell is negative.
Order
A − B ≠ B − A
Subtraction is not commutative — keep the operand order clear.
Shared row
Avoid [[0] * cols] * rows
That reuses one row. Prefer [[0] * cols for _ in range(rows)].
Analysis
Time and Space Complexity
Program
Time
Extra space
Nested loops
O(m × n)
O(1) besides result
Shape-safe subtract
O(m × n)
O(1) besides result
Every cell is touched exactly once. The result matrix needs O(m × n) space to store the answer.