Python program to subtract two matrices has been shown here. Two matrices $[A]_{m \times n}$ and $[B]_{p \times q}$ are considered for Subtraction if the number of rows and columns are same in both of the matrices i.e. $m = p$ and $n = q$.

#### Page content(s):

1. Program & Output: Iterative approach

1. Algorithm

2. Pseudocode

3. Time Complexity

## 1. Python Program for matrix Subtraction

Code has been copied
#***************************************
#        alphabetacoder.com
#  Python program for Matrix Subtraction
#***************************************

# take input of the order of first matrix
print("Enter the number of rows and columns of first matrix=")
m, n=map(int, input().split())

# declare first matrix of m x n order with zero initialization
A = [[0 for j in range(n)] for i in range(m)]

print("Enter the first matrix of order ",m," x ",n,"=")
#take input of the elements first matrix
for i in range(m):
for j in range(n):
A[i][j]=int(input())

#take input of the order of second matrix
print("Enter the number of rows and columns of second matrix=")
p, q=map(int, input().split())

# declare second matrix of p x q order with zero initialization
B = [[0 for j in range(q)] for i in range(p)]

#take input of the second matrix
print("Enter the second matrix of order ",p," x ",q,"=");
for i in range(p):
for j in range(q):
B[i][j]=int(input())

# check if orders of matrices are same
# if the orders are same then do addition
if m!=p or n!=q:
print("Matrices are of different order, hence not equal")
else:
#check equality of each corresponding elements
print("The resultant matrix after subtraction:")
for i in range(m):
for j in range(n):
#end=" " prints elements without new line
print(A[i][j]-B[i][j],end=" ")
#for new line
print("")


Output

#### Case 1:

Enter the number of row and column of first matrix=2 3

Enter the first matrix of order 2 x 3=

3

4

0

4

1

2

Enter the number of row and column of second matrix=2 3

Enter the second matrix of order 2 x 3=

1

2

4

4

7

0

The resultant matrix after subtraction:=

2 2 -4

0 -6 2

#### Case 2:

Enter the number of row and column of first matrix=2 2

Enter the first matrix of order 2 x 2=

3

4

0

4

Enter the number of row and column of second matrix=2 1

Enter the second matrix of order 2 x 1=

9

3

Matrices are of different order,hence subtraction is not possible