Definition
Entrywise −
Each output cell is A minus B at the same index.
Element-wise matrix subtraction subtracts matching cells: C[i][j] = A[i][j] - B[i][j], only when shapes match. This tutorial covers the rule, nested loops, negatives, a live preview, worked Python examples, edge cases, and complexity.
Entrywise −
Each output cell is A minus B at the same index.
m × n both
Subtraction is defined only when dimensions match.
Not A = B
A − B differs from B − A (they are negatives).
Signed cells
Result entries can be negative — that is normal.
Show 3×3
Run the classic 3×3 sample difference in the browser.
A + (−B)
Same nested-loop pattern as addition, different operator.
Matrix subtraction on this page means element-wise difference: if A and B are both m × n, then C[i][j] = A[i][j] - B[i][j] for every cell.
Shapes must match. Order matters: B - A = -(A - B). You can also think of it as A + (-B) entrywise.
It reuses the same nested-loop pattern as addition while highlighting negatives and non-commutativity — great interview follow-ups.
Top-left subtracts top-left — never mix cells.
Signed results are expected when A < B.
Visit each cell once and subtract.
Different rules from row–column products.
In short: if shapes match, set C[i][j] = A[i][j] - B[i][j] with nested loops; expect negatives.
Given two equal-sized matrices A and B, build C where each cell is the difference of corresponding cells.
# [[5, 8], [7, 4]] - [[3, 1], [6, 9]] = [[2, 7], [1, -5]]
# Same shape required; order matters (A - B ≠ B - A) | Item | Type | Description |
|---|---|---|
A, B | list[list[int]] | Two matrices with the same shape. |
| Return / print | matrix / text | Result matrix with entrywise differences (may include negatives). |
function subtract_matrices(A, B):
for each row i:
for each column j:
C[i][j] <- A[i][j] - B[i][j]
return C | Method | Idea | Notes |
|---|---|---|
| Nested loops | C[i][j] = A[i][j] - B[i][j] | Interview default — clear indexing |
| Via negation | A + (-B) entrywise | Same result; useful math intuition |
| Matrix product | Row–column dots | Different operation — not this page |
| Goal | Pattern |
|---|---|
| Subtract cell | out[i][j] = a[i][j] - b[i][j] |
| Traverse | for i in range(rows): for j in range(cols) |
| Build rows | row.append(...); result.append(row) |
| Fresh grid | [[0 for _ in range(cols)] for _ in range(rows)] |
| Shape check | Same rows and uniform column lengths |
| Order reminder | B - A = -(A - B) |
Same nested loops for +/− — different rules for products.
A[i][j] - B[i][j]This page — same shape required
A[i][j] + B[i][j]Same traversal; different operator
sum A[i][k]*B[k][j]Different shape rule and formula
mention orderSay A − B is not B − A
Reach for element-wise subtraction when grids differ cell by cell.
Same loops as addition, plus negatives and order.
Natural return to entrywise ops in this chain.
Compare two tables cell by cell (deltas, errors).
Practice printing and reasoning about negatives.
Clarify when the interviewer wants true matrix multiply.
Key benefit: one short 2D problem that locks in indexing, same-shape checks, and non-commutative order.
Uses the same 3×3 sample as Example 1. Click to print Matrix 1, Matrix 2, and Matrix1 − Matrix2.
Three complete Python programs — classic 3×3 difference, easy 2×2 check, and a shape-safe general subtractor. Click View Output to reveal sample console results.
Two nested loops and one subtraction per cell — negatives included.
subtract_matrices computes matrix1 − matrix2. Some output values are negative, which is expected.
def subtract_matrices(mat1: list[list[int]], mat2: list[list[int]]) -> list[list[int]]:
result = []
for i in range(3):
row = []
for j in range(3):
row.append(mat1[i][j] - mat2[i][j])
result.append(row)
return result
def display_matrix(matrix: list[list[int]]) -> None:
for row in matrix:
print("\t".join(str(x) for x in row))
def main() -> None:
matrix1 = [
[5, 8, 2],
[7, 4, 9],
[3, 6, 1],
]
matrix2 = [
[3, 1, 7],
[6, 9, 2],
[8, 5, 4],
]
result_matrix = subtract_matrices(matrix1, matrix2)
print("Matrix 1:")
display_matrix(matrix1)
print("\nMatrix 2:")
display_matrix(matrix2)
print("\nResultant Matrix (Matrix1 - Matrix2):")
display_matrix(result_matrix)
if __name__ == "__main__":
main() Every result cell performs exactly one subtraction from matching positions. Top-right is 2 - 7 = -5 — negatives are correct, not bugs.
Smaller matrix, same logic — good for quick interview dry-run.
Compact example showing both negative and positive result cells.
ROWS = 2
COLS = 2
def subtract_matrices(a: list[list[int]], b: list[list[int]]) -> list[list[int]]:
out = [[0 for _ in range(COLS)] for _ in range(ROWS)]
for i in range(ROWS):
for j in range(COLS):
out[i][j] = a[i][j] - b[i][j]
return out
def print_matrix(title: str, m: list[list[int]]) -> None:
print(title)
for row in m:
print(*row)
def main() -> None:
a = [[1, 2], [3, 4]]
b = [[4, 3], [2, 1]]
c = subtract_matrices(a, b)
print_matrix("A", a)
print()
print_matrix("B", b)
print()
print_matrix("A - B", c)
if __name__ == "__main__":
main() Top-left is 1 - 4 = -3; bottom-right is 4 - 1 = 3. Matching the printed A − B confirms the cell-by-cell rule.
Generalize beyond fixed sizes with a same-shape guard.
Checks matching shapes, then subtracts with a comprehension.
def same_shape(a: list[list[int]], b: list[list[int]]) -> bool:
if not a or not b or len(a) != len(b):
return False
cols = len(a[0])
if cols == 0:
return False
for row in a + b:
if len(row) != cols:
return False
return True
def subtract_safe(a: list[list[int]], b: list[list[int]]) -> list[list[int]] | None:
if not same_shape(a, b):
return None
rows, cols = len(a), len(a[0])
return [[a[i][j] - b[i][j] for j in range(cols)] for i in range(rows)]
ok = subtract_safe([[5, 8, 2], [7, 4, 9], [3, 6, 1]], [[3, 1, 7], [6, 9, 2], [8, 5, 4]])
bad = subtract_safe([[1, 2], [3, 4]], [[5, 6, 7]])
print(ok)
print(bad) Shape checks catch bad input before any subtraction. Returning None (or raising) is clearer than an IndexError mid-loop.
Both matrices must have the same rows and columns.
For each i and j, assign C[i][j] = A[i][j] - B[i][j].
If A is smaller than B at a cell, the result is negative.
C has the same shape as A and B.
Trace the first row for Example 1: [5, 8, 2] - [3, 1, 7].
| (i, j) | A | B | C |
|---|---|---|---|
(0, 0) | 5 | 3 | 2 |
(0, 1) | 8 | 1 | 7 |
(0, 2) | 2 | 7 | -5 |
First row of the result is [2, 7, -5] — matching Example 1 output.
Where element-wise matrix subtraction shows up beyond the interview prompt.
2D indexing plus signed results.
Example: write subtract_matrices(A, B).
Return to entrywise ops after products.
Example: swap * loops for −.
Compare two grids cell by cell.
Example: forecast − actual.
Relate A − B to A + (−B).
Example: flip B then add.
Show B − A is the negative of A − B.
Example: dry-run both orders.
Next page flips rows and columns.
Example: continue the matrix chain.
Pro Tip: open with “element-wise subtraction, same shape, A − B not B − A” before writing loops.
Why this pattern works well in interviews and classwork.
One cell rule: C[i][j] = A[i][j] - B[i][j].
Same nested loops you already know from matrix addition.
Non-commutativity is a natural interview follow-up.
2×2 samples verify understanding in seconds.
Pro Tip: lead with loops and same-shape; mention NumPy A - B only as a production aside.
Small habits that keep matrix-subtraction solutions interview-ready.
Avoid confusion with matrix multiplication.
Reject mismatched dimensions early.
Do not treat negative cells as errors.
Avoid [[0]*cols]*rows shared references.
One subtraction (and visit) per cell.
Pro Tip: dry-run 2 - 7 = -5 aloud on the 3×3 sample — if that matches, your indexing is correct.
Mistakes that commonly break matrix-subtraction solutions.
Subtracting matrices with different sizes.
→ Validate rows and columns first.
Computing B − A when A − B was asked.
→ Subtract in the requested order only.
Using triple loops or dot products by mistake.
→ Say “element-wise” and stick to matching cells.
Assuming all result cells must be positive.
→ Negatives are valid when A < B at a cell.
[[0]*cols]*rows shares row lists.
→ Build each row separately.
Common mistakes to avoid — plus a few more.
Subtraction is valid only when dimensions are identical.
A − B and B − A are different results.
Expected when A[i][j] < B[i][j] — not an error.
Validate every row length equals cols.
Equal matching entries yield 0 — still valid.
Still uses the same formula — one subtraction.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
C[i][j] = A[i][j] - B[i][j] for same-shaped matrices.A - B = A + (-B) entrywise.Quick Takeaway: same shape, then C[i][j] = A[i][j] - B[i][j] with nested loops; order matters and negatives are fine.
| Operation | Time | Extra space |
|---|---|---|
Subtract two m × n matrices | O(m*n) | O(1) besides result matrix |
| Shape validation | O(m) row checks | O(1) |
| In-place overwrite | O(m*n) | O(1) if originals unused |
As matrix size grows, runtime grows proportionally to the number of cells.
Element-wise matrix subtraction subtracts matching cells when shapes match. Use nested loops, expect negatives, and remember that A − B is not the same as B − A.
Practice the three examples above, then continue to matrix transpose for the next 2D operation.
Same shape first, then C[i][j] = A[i][j] - B[i][j]; order matters.
Subtract matrices the interview-friendly way.
Entrywise −
DefinitionSame m × n
ConstraintA−B ≠ B−A
PropertyNegatives OK
OutputO(m·n)
AnalysisMatrix subtraction is entrywise like addition: (A - B)ij = Aij - Bij. It is equivalent to A + (-B), and both matrices must have the same shape.
Learn how to flip rows and columns to build the transpose of a matrix.
8 people found this page helpful