How to Calculate the Sum of Two Matrices
How to Calculate the Sum of Two Matrices
How to Calculate the Sum of Two Matrices
I have two matrices and I need to calculate their sum. How can I implement this in Python?
solveurit24@gmail.com Changed status to publish February 16, 2025
You can create a new matrix where each element is the sum of corresponding elements from the two input matrices.
Code Example:
def matrix_addition(matrix1, matrix2):
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[i])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result
matrix1 = [
[1, 2],
[3, 4]
]
matrix2 = [
[5, 6],
[7, 8]
]
print(matrix_addition(matrix1, matrix2))
# Output:
# [[6, 8], [10, 12]]This function adds two matrices of the same dimensions and returns the resulting matrix.
solveurit24@gmail.com Changed status to publish February 16, 2025