NumPy: Compute the inverse of a given matrix
12. Inverse of a Matrix
Write a NumPy program to compute the inverse of a given matrix.
Sample Solution :
Python Code :
Sample Output:
Original matrix: [[1 2] [3 4]] Inverse of the said matrix: [[-2. 1. ] [ 1.5 -0.5]]
Explanation:
m = np.array([[1,2],[3,4]]): This statement creates a 2x2 NumPy array m with the specified elements.
result = np.linalg.inv(m): This line computes the inverse of the matrix m. The inverse of a square matrix A (if it exists) is another matrix, denoted as A^(-1), such that their product results in the identity matrix (A * A^(-1) = I). In this case, the inverse of the 2x2 matrix m is calculated as follows:
1/(ad-bc) * [[d, -b], [-c, a]]
where a, b, c, and d are the elements of the matrix, and ad-bc is the determinant.
For the given matrix m, the inverse is calculated as:
1/((1*4)-(2*3)) * [[4, -2], [-3, 1]]
1/(-2) * [[4, -2], [-3, 1]]
-0.5 * [[4, -2], [-3, 1]]
resulting in the inverse matrix [[-2., 1.], [1.5, -0.5]].
For more Practice: Solve these Related Problems:
- Compute the inverse of a square matrix using np.linalg.inv and validate by checking the product with the original matrix.
- Implement a function that attempts to compute the inverse of a nearly singular matrix and handles exceptions gracefully.
- Test the inverse function on matrices with complex numbers and verify that A * A_inv equals the identity matrix.
- Compare the results of np.linalg.inv with the inverse computed via the adjugate method for small matrices.
Go to:
PREV : Determinant of an Array
NEXT : QR Decomposition
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.