Matrix Addition: Add Two Matrices of any Dimension using Python3?

In this Python tutorial, we will learn about how to add matrix in Python. Learn how to perform matrix addition in Python with an easy example.

MATRIX ADDITION in Python

Matrix Addition is the addition of two or more than two matrices with the same dimension. Understanding this code will also benefit you to understand the subtraction of two matrices.

Conditions that are necessary for both addition and subtraction of matrices:

• It doesn’t require to be a square matrix i.e., the number of rows, m can equal or not equal to the number of columns, n.
• All the matrix should be of the same dimension i.e., m and n should be fixed for all the matrices. Now let’s notice the code snippet.

Program:

r=int(input("Enter number of Rows: "))
c=int(input("Enter number of Columns: "))
A=[[0 for i in range(c)] for j in range(r)] #initialize A matrix of dimension rxc
B=[[0 for i in range(c)] for j in range(r)] #initialize B matrix of dimension rxc
C=[[0 for i in range(c)] for j in range(r)] #initialize C matrix of dimension rxc
print("Enter Matrix Elements of A:")
#input matrix A
for i in range(r):
for j in range(c):
x=int(input())
A[i][j]=x
#input matrix B
print("Enter Matrix Elements of B:")
for i in range(r):
for j in range(c):
x=int(input())
B[i][j]=x
#Add matrices A and B
for i in range(r):
for j in range(c):
C[i][j]=A[i][j]+B[i][j]
for i in range(r):
for j in range(c):
print(C[i][j],end=" ")
print()

Output 1:

Enter number of Rows: 3
Enter number of Columns: 3
Enter Matrix Elements of A:
1
2
3
4
5
6
7
8
9
Enter Matrix Elements of B:
1
4
9
16
25
36
49
64
81
2 6 12
20 30 42
56 72 90

Output 2:

Enter number of Rows: 4
Enter number of Columns: 2
Enter Matrix Elements of A:
1
2
3
4
5
6
7
8
Enter Matrix Elements of B:
9
8
7
6
5
4
3
2
10 10
10 10
10 10
10 10