Like matrix addition, subtraction is also one of the most basic operations that we perform on two or more matrices. The only condition to add or subtract two matrices is that both should have the same dimensions which means both matrices should have the same number of rows and columns.
Now to subtract two matrices you just need to find the difference between corresponding entries and place the result at the corresponding position in the resultant matrix.
Suppose A = [aij]mxn
and B = [bij]mxn
are two matrices of order m x n, then the differnce of A and B is given by;
A - B = [aij]mxn - [bij]mxn = [aij - bij]mxn
In this article, you will see the python code to find the difference between two matrices.
Python program for subtraction of two matrices
There are multiple ways in which you can perform the same task in programming. The two most common methods to subtract one matrix from another are –
- Using nested for loop
- Using list comprehension
Using nested for loop
Here we will iterate through all the elements of both matrices by using nested for loop one by one, subtracting them, and storing each element at their corresponding positions in a third matrix.
# Python program to subtract two matrices using nested for loops
matrix1 = [[1,0,-1],
[3 ,8,6],
[6 ,9,2]]
matrix2 = [[0,2,4],
[7,-9,3],
[4,0,1]]
matrix_diff = [[0,0,0],
[0,0,0],
[0,0,0]]
# Iterate through matrix rows
for i in range(len(matrix1)):
# Iterate through matrix columns
for j in range(len(matrix1[0])):
# Subtraction of matrix elements
matrix_diff[i][j] = matrix1[i][j] - matrix2[i][j]
for r in matrix_diff:
print(r)
print("\n")
Save this file with the .py extension and then run this program you will see the given output :
Using list comprehension
This method provides a shorter way to do the same task. Here we will use list comprehension to subtract two given matrices.
# Python program to subtract two matrices using list comprehension
matrix1 = [[1,8,3],
[0 ,-5,7],
[7 ,0,5]]
matrix2 = [[0,6,1],
[6,9,0],
[1,2,9]]
# Subtraction of matrix elements
matrix_diff = [[matrix1[i][j] - matrix2[i][j] for j in range(len(matrix1[0]))] for i in range(len(matrix1))]
for r in matrix_diff:
print(r)
You will see the given output in your terminal –
So now I hope you are able to find subtraction of two matrices using Python code. If you have a query or feedback then write us in the comments below.