Perform Matrix Subtraction in Python
What you’ll learn
- The element-wise rule C[i][j] = A[i][j] - B[i][j] for same-sized matrices.
- A complete 3x3 Python program and a compact 2x2 version.
- How subtraction relates to addition:
A - B = A + (-B).
Overview
Subtracting matrices means subtracting matching positions, one by one. It works only when both matrices have equal row and column counts.
Two examples
A 3x3 walkthrough and a 2x2 quick-check program.
Live preview
See the same sample subtraction done in-browser.
Negative values
Result entries can be negative, and that is normal.
Prerequisites
Basic loops and list indexing in Python.
- Know matrix representation as list-of-lists, like
[[1, 2], [3, 4]]. - Understand that subtraction can produce negative numbers.
What is matrix subtraction?
If A and B have the same dimensions, then C = A - B where each result cell is C[i][j] = A[i][j] - B[i][j].
You can also think of it as adding the negative matrix: A + (-B).
Live preview
Uses the same 3x3 sample as code example 1. Click to print Matrix 1, Matrix 2, and Matrix1 - Matrix2.
Algorithm
Goal: compute C[i][j] = A[i][j] - B[i][j] for every matrix cell.
Check dimensions
Both matrices must have same row and column counts.
Nested loops
For each i and j, assign result[i][j] = A[i][j] - B[i][j].
Display result
Print row by row for easy visual validation.
📜 Pseudocode
function subtract_matrices(A, B):
for each row i:
for each column j:
C[i][j] <- A[i][j] - B[i][j]
return C Subtract two 3x3 matrices (program with explanation)
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() Explanation
Every result cell performs exactly one subtraction from matching positions.
Subtract two 2x2 matrices
Smaller matrix, same logic. Good for quick interview dry-run.
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() Explanation
This compact example shows both negative and positive result cells.
Notes
In-place option. You can overwrite one matrix if you no longer need original values.
Shape checks. For dynamic input, validate equal dimensions before subtraction.
❓ FAQ
🔄 Input / output
These examples use hardcoded matrices. For user input, collect rows into lists and ensure both matrices have matching dimensions.
Edge cases
Common mistakes to avoid:
Mismatched matrices
Subtraction is valid only when dimensions are identical.
Wrong operand order
A - B and B - A are different results.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
Subtract two m x n matrices | O(m*n) | O(1) besides result matrix |
Summary
- Definition:
C[i][j] = A[i][j] - B[i][j]for same-shaped matrices. - Code: two nested loops and one subtraction per cell.
- Relation:
A - B = A + (-B)entrywise.
Matrix subtraction is entrywise like addition: (A - B)ij = Aij - Bij. It is equivalent to A + (-B), and both matrices must have the same shape.
8 people found this page helpful
