Add n number of matrix in Python:-
Inorder to add multiple matrices in Python each matrix should be of the same dimensions.
The addition of matrices is done element-wise that means each element in the resulting matrix is the sum of the corresponding elements in the matrices being added. Check Dimensions that means ensure all matrices have the same dimensions. This is crucial because matrix addition is only defined for matrices of the same size
then secondly we have to initialize a result matrix that means creating a result matrix initialized with zeros, having the same dimensions as the input matrices.
then thirdly we have to add matrices Element-wise Loop through each element position and add the corresponding elements from all matrices, storing the result in the corresponding position of the result matrix.
def add_matrices(*matrices):
if not matrices:
raise ValueError(“No matrices provided for addition”)
num_rows = len(matrices[0])
num_cols = len(matrices[0][0])
for matrix in matrices:
if len(matrix) != num_rows or any(len(row) != num_cols for row in matrix):
raise ValueError(“All matrices must have the same dimensions”)
result = [[0 for _ in range(num_cols)] for _ in range(num_rows)]
for matrix in matrices:
for i in range(num_rows):
for j in range(num_cols):
result[i][j] += matrix[i][j]
return result
# for example
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
matrix3 = [
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]
]
result_matrix = add_matrices(matrix1, matrix2, matrix3)
for row in result_matrix:
print(row)