Matrix Addition in Python.
Matrix addition is possible only when the matrices meet specific conditions related to their dimensions. For two matrices A and B to be added together (A + B = C), they must satisfy the following conditions:
- Both matrices must have the same number of rows and columns.
- If matrix A has dimensions m x n (m rows and n columns), matrix B must also have dimensions m x n.
Python Code for Adding Two Matrices.
# Python Code for Matrix Addition def add_matrices(matrix1, matrix2): # Check if matrices have the same dimensions if len(matrix1) != len(matrix2) or len(matrix1[0]) != len(matrix2[0]): return "Matrices should have the same dimensions for addition" 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 # Example matrices for addition matrix_A = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] matrix_B = [ [9, 8, 7], [6, 5, 4], [3, 2, 1] ] # Calling the function to add matrices resultant_matrix = add_matrices(matrix_A, matrix_B) print("Resultant Matrix after Addition:") for row in resultant_matrix: print(row)
Resultant Matrix after Addition:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Explanation: The add_matrices() function takes two matrices as input parameters and checks if they have the same dimensions. If the matrices have the same dimensions, it iterates through corresponding elements of the matrices, performs element-wise addition, and constructs the resultant matrix.
- Time Complexity: O(m x n)
- Space Complexity: O(m x n)
No comments:
Post a Comment