The addition of two matrices in Python is a simple process where we add each element of both the matrix and create a resulted matrix. In this article, we used several ways to create a Python program for two matrix addition such as:
List comprehension
Numpy.add Function
Let's get started.
In this program, we used list comprehension to add two matrices and store the result into a third matrix. See the Python code.
# Python Program to Add Two Matrix
# Take two Matrices
matrix1 = [ [3,1],
[2,4],
[2,2]
]
matrix2 = [ [5, 7],
[1, 2],
[5, 1]
]
# Matrix to store result
result = [[0,0],[0,0],[0,0]]
# Adding two matrices using list comprehension in Python
result = [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix2[0]))] for i in range(len(matrix1))]
# Print Result
for r in result:
print(r)
Output:
[8, 8]
[3, 6]
[7, 3]
This is one of the oldest approaches that most of us have used in C language to add two arrays. We used two for loop two traverse each element of the matrixes and then added them all. See the Python code.
# Python Program to Add Two Matrix
# Take two Matrices
matrix1 = [ [3,1],
[2,4],
[2,2]
]
matrix2 = [ [5, 7],
[1, 2],
[5, 1]
]
# Matrix to store result
result = [[0,0],[0,0],[0,0]]
# Adding two matrices using for loop in Python
for i in range(len(matrix1)):
#for columns
for j in range(len(matrix1[0])):
result[i][j] = matrix1[i][j] + matrix2[i][j]
# Print Result
for r in result:
print(r)
Output:
[8, 8]
[3, 6]
[7, 3]
The Numpy is a Python library that is used to deal with arrays and related data structures. Here, we used add() method of this library that returns the sum of two arrays. See the Python code.
# Python Program to Add Two Matrix
import numpy as np
# Take two Matrices
matrix1 = [ [3,1],
[2,4],
[2,2]
]
matrix2 = [ [5, 7],
[1, 2],
[5, 1]
]
# Matrix to store result
result = [[0,0],[0,0],[0,0]]
# Adding two matrices using numpy.add() method
result = np.add(matrix1, matrix2)
# Print Result
for r in result:
print(r)
Output:
[8, 8]
[3, 6]
[7, 3]