In this tutorial, we will learn how to add two matrices in Python. We will cover the basic concept of matrix addition and implement a function to perform the operation.
Matrix addition is the process of adding two matrices by adding the corresponding entries together. The two matrices must have the same dimensions for the addition to be possible.
The syntax to add two matrices in Python is:
def add_matrices(matrix1, matrix2):
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result
We can create a function to add two matrices element-wise by iterating through their elements and adding the corresponding entries.
For example,
add_matrices
that takes two parameters matrix1
and matrix2
.result
to store the sum of the matrices.for
loop to iterate through the elements of the matrices.matrix1
and matrix2
and append the sum to a new row.result
list.result
matrix.def add_matrices(matrix1, matrix2):
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result
# Sample matrices
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix2 = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
# Add the matrices
result = add_matrices(matrix1, matrix2)
# Print the result
print('Sum of the matrices is:')
for row in result:
print(row)
Sum of the matrices is: [10, 10, 10] [10, 10, 10] [10, 10, 10]