0
0
PythonProgramBeginner · 2 min read

Python Program to Subtract Two Matrices

To subtract two matrices in Python, use nested loops to subtract corresponding elements like result[i][j] = matrix1[i][j] - matrix2[i][j].
📋

Examples

Inputmatrix1 = [[1, 2], [3, 4]], matrix2 = [[4, 3], [2, 1]]
Output[[-3, -1], [1, 3]]
Inputmatrix1 = [[5, 5, 5], [5, 5, 5]], matrix2 = [[1, 2, 3], [4, 5, 6]]
Output[[4, 3, 2], [1, 0, -1]]
Inputmatrix1 = [[0]], matrix2 = [[0]]
Output[[0]]
🧠

How to Think About It

To subtract two matrices, think of them as grids of numbers. You take each number in the first grid and subtract the matching number in the second grid at the same position. This means you go row by row and column by column, subtracting each pair of numbers to build a new grid with the results.
📐

Algorithm

1
Get the two matrices as input.
2
Create an empty matrix to store the result with the same size.
3
For each row index, do:
4
For each column index in that row, subtract the element of the second matrix from the first matrix.
5
Store the subtraction result in the new matrix at the same position.
6
Return or print the resulting matrix.
💻

Code

python
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))
Output
[[-3, -1], [1, 3]]
🔍

Dry Run

Let's trace the example matrices [[1, 2], [3, 4]] and [[4, 3], [2, 1]] through the code.

1

Initialize variables

rows = 2, cols = 2, result = []

2

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]]

3

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]]

4

Return result

Return [[-3, -1], [1, 3]]

ijmatrix1[i][j]matrix2[i][j]result[i][j]
0014-3
0123-1
10321
11413
💡

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

Using list comprehension
python
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))
This method is shorter and more Pythonic but may be harder to read for beginners.
Using numpy library
python
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[4, 3], [2, 1]])
result = matrix1 - matrix2
print(result.tolist())
Using numpy is efficient and simple for large matrices but requires installing an external library.

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.

ApproachTimeSpaceBest For
Nested loopsO(n*m)O(n*m)Beginners and clarity
List comprehensionO(n*m)O(n*m)Concise Python code
Numpy libraryO(n*m)O(n*m)Large matrices and performance
💡
Always check that both matrices have the same size before subtracting to avoid errors.
⚠️
Trying to subtract matrices of different sizes without validation causes index errors.