Python Program to Add Two Matrices
A matrix is simply defined as some arrangement of numbers that are formed by using columns and rows. In Python, we use a list of lists to represent a matrix.
If each element of the list is itself a list then it would be a matrix addition in python. For instance, [[1,2,3],[3,5,3], [7,9,10]] is a 3×3 matrix i.e. it has 3 rows and 3 columns.
Matrix Addition
The number of rows and columns in a matrix determines its dimensions. For example, [2, 3, 4, 5, 22, 24] is a one-dimensional array while [[2,3], [4,5], [22,24]] is a 2-dimensional array. Following is an example of a 3×3 matrix:
[
[1,2,3],
[3,5,3],
[7,9,10]
]
To add two matrices their dimensions should be similar. For example, you can add a 2×3 matrix only with another matrix with 2 rows and 3 columns.
Prerequisites to Create the Python Program to Add Two Matrices In order to comprehend and write the program for matrix addition, you need to have a sound understanding of the following concepts in Python:
- Input/Output
- Lists
- Looping
- List comprehension
Python Program to Add Two Matrices
Code:
#matrix addition in python
rows = int(input("Enter the Number of rows : " ))
column = int(input("Enter the Number of Columns: "))
print("Enter the elements of First Matrix:")
matrix_a= [[int(input()) for i in range(column)] for i in range(rows)]
print("First Matrix is: ")
for n in matrix_a:
print(n)
print("Enter the elements of Second Matrix:")
matrix_b= [[int(input()) for i in range(column)] for i in range(rows)]
for n in matrix_b:
print(n)
result=[[0 for i in range(column)] for i in range(rows)]
for i in range(rows):
for j in range(column):
result[i][j] = matrix_a[i][j]+matrix_b[i][j]
print("The Sum of Above two Matrices is : ")
for r in result:
print(r)
Sample Output 1:
Enter the Number of rows : 3
Enter the Number of Columns: 3
Enter the elements of First Matrix:
2
4
6
7
2
9
23
12
35
First Matrix is:
[2, 4, 6]
[7, 2, 9]
[23, 12, 35]
Enter the elements of Second Matrix:
6
20
10
14
15
28
29
40
11
[6, 20, 10]
[14, 15, 28]
[29, 40, 11]
The Sum of the Above two Matrices is :
[8, 24, 16]
[21, 17, 37]
[52, 52, 46]
Sample Output 2:
Enter the Number of rows : 2
Enter the Number of Columns: 4
Enter the elements of First Matrix:
1
2
3
4
5
6
7
8
First Matrix is:
[1, 2, 3, 4]
[5, 6, 7, 8]
Enter the elements of Second Matrix:
10
12
24
12
34
54
2
34
[10, 12, 24, 12]
[34, 54, 2, 34]
The Sum of the Above two Matrices is :
[11, 14, 27, 16]
[39, 60, 9, 42]
Conclusion
That was all about adding two matrices in Python. You are free to tweak the code to learn more about the concept of matrix addition. You can also get creative and implement the program in some other way that you find suitable and feasible.