Python Program to Subtract Two Matrices
result[i][j] = matrix1[i][j] - matrix2[i][j].Examples
How to Think About It
Algorithm
Code
def subtract_matrices(matrix1, matrix2): rows = len(matrix1) cols = len(matrix1[0]) result = [] for i in range(rows): row = [] for j in range(cols): row.append(matrix1[i][j] - matrix2[i][j]) result.append(row) return result # Example usage matrix1 = [[1, 2], [3, 4]] matrix2 = [[4, 3], [2, 1]] print(subtract_matrices(matrix1, matrix2))
Dry Run
Let's trace the example matrices [[1, 2], [3, 4]] and [[4, 3], [2, 1]] through the code.
Initialize variables
rows = 2, cols = 2, result = []
First row subtraction
i = 0, row = [] Subtract matrix1[0][0] - matrix2[0][0] = 1 - 4 = -3 row = [-3] Subtract matrix1[0][1] - matrix2[0][1] = 2 - 3 = -1 row = [-3, -1] Append row to result: result = [[-3, -1]]
Second row subtraction
i = 1, row = [] Subtract matrix1[1][0] - matrix2[1][0] = 3 - 2 = 1 row = [1] Subtract matrix1[1][1] - matrix2[1][1] = 4 - 1 = 3 row = [1, 3] Append row to result: result = [[-3, -1], [1, 3]]
Return result
Return [[-3, -1], [1, 3]]
| i | j | matrix1[i][j] | matrix2[i][j] | result[i][j] |
|---|---|---|---|---|
| 0 | 0 | 1 | 4 | -3 |
| 0 | 1 | 2 | 3 | -1 |
| 1 | 0 | 3 | 2 | 1 |
| 1 | 1 | 4 | 1 | 3 |
Why This Works
Step 1: Matrix size determination
We find the number of rows and columns to know how many elements to process using len(matrix1) and len(matrix1[0]).
Step 2: Nested loops for element-wise subtraction
We use two loops: outer for rows and inner for columns to access each element by its position.
Step 3: Subtract corresponding elements
At each position, we subtract the element of the second matrix from the first using matrix1[i][j] - matrix2[i][j].
Step 4: Build the result matrix
We collect the subtraction results in a new matrix to keep the original matrices unchanged.
Alternative Approaches
def subtract_matrices(matrix1, matrix2): return [[matrix1[i][j] - matrix2[i][j] for j in range(len(matrix1[0]))] for i in range(len(matrix1))] matrix1 = [[1, 2], [3, 4]] matrix2 = [[4, 3], [2, 1]] print(subtract_matrices(matrix1, matrix2))
import numpy as np matrix1 = np.array([[1, 2], [3, 4]]) matrix2 = np.array([[4, 3], [2, 1]]) result = matrix1 - matrix2 print(result.tolist())
Complexity: O(n*m) time, O(n*m) space
Time Complexity
The program loops through each element of the matrices once, so the time depends on the number of rows (n) times columns (m), resulting in O(n*m).
Space Complexity
A new matrix of the same size is created to store results, so space complexity is also O(n*m).
Which Approach is Fastest?
Using numpy is fastest for large matrices due to optimized C code, while list comprehension is faster than nested loops in pure Python.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops | O(n*m) | O(n*m) | Beginners and clarity |
| List comprehension | O(n*m) | O(n*m) | Concise Python code |
| Numpy library | O(n*m) | O(n*m) | Large matrices and performance |