In matrix subtraction, elements of one matrix are subtracted from their corresponding elements in another matrix of the same dimensions. The result is a new matrix with dimensions identical to the original matrices being subtracted.
Quick Tip: Ensure matrices have the same dimensions for subtraction (m x n).
Matrix Subtraction Program in Python.
Step-by-step Algorithm:
- Define two matrices A and B, each represented as nested lists in Python.
- Create a new matrix to store the result of the subtraction.
- Subtract corresponding elements of matrices A and B to obtain the elements of the resultant matrix.
- Use nested loops to iterate through each element in the matrices and perform subtraction.
Python Code:
# Python code for matrix subtraction def subtract_matrices(matrix_A, matrix_B): result_matrix = [] for i in range(len(matrix_A)): row = [] for j in range(len(matrix_A[0])): row.append(matrix_A[i][j] - matrix_B[i][j]) result_matrix.append(row) return result_matrix # Example usage matrix_A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] matrix_B = [[9, 8, 7], [6, 5, 4], [3, 2, 1]] result = subtract_matrices(matrix_A, matrix_B) print("Resultant Matrix after subtraction:") for row in result: print(row)
Resultant Matrix after subtraction:
[-8, -6, -4]
[-2, 0, 2]
[4, 6, 8]
- Time Complexity: O(m x n) where m is the number of rows and n is the number of columns.
- Space Complexity: O(m x n) because we need extra space to store the resultant matrix.
No comments:
Post a Comment