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

Algorithm, pseudocode and time complexity of the program have also been shown.

#### Page content(s):

1. Program & Output: Iterative approach

#### Additional content(s):

1. Algorithm

2. Pseudocode

3. Time Complexity

## 1. Python Program for matrix addition

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

# 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 addition:")
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 addition:=

4 6 4

8 8 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 addition is not possible

#### Post a Comment

If you have any doubts or suggestions, please leave a note.