Python Program to Find Inverse of Matrix
numpy.linalg.inv() function like this: import numpy as np; inv_matrix = np.linalg.inv(matrix).Examples
How to Think About It
Algorithm
Code
import numpy as np def find_inverse(matrix): try: inv = np.linalg.inv(matrix) return inv except np.linalg.LinAlgError: return "Matrix is singular and cannot be inverted." matrix = np.array([[1, 2], [3, 4]]) inverse = find_inverse(matrix) print(inverse)
Dry Run
Let's trace the example matrix [[1, 2], [3, 4]] through the code
Input matrix
matrix = [[1, 2], [3, 4]]
Call np.linalg.inv
Calculate inverse of matrix
Compute inverse
Inverse matrix = [[-2.0, 1.0], [1.5, -0.5]]
Return result
Return the inverse matrix
| Step | Operation | Result |
|---|---|---|
| 1 | Input matrix | [[1, 2], [3, 4]] |
| 2 | Calculate inverse | [[-2.0, 1.0], [1.5, -0.5]] |
| 3 | Return inverse | [[-2.0, 1.0], [1.5, -0.5]] |
Why This Works
Step 1: Check matrix invertibility
The code uses np.linalg.inv() which internally checks if the matrix is square and has a non-zero determinant before computing the inverse.
Step 2: Calculate inverse
If the matrix is invertible, np.linalg.inv() calculates the inverse matrix using numerical methods.
Step 3: Handle errors
If the matrix is singular (not invertible), the function raises an exception which is caught to return a friendly message.
Alternative Approaches
def manual_inverse(matrix): det = matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] if det == 0: return "Matrix is singular and cannot be inverted." inv = [[matrix[1][1]/det, -matrix[0][1]/det], [-matrix[1][0]/det, matrix[0][0]/det]] return inv matrix = [[1, 2], [3, 4]] print(manual_inverse(matrix))
from scipy.linalg import inv import numpy as np matrix = np.array([[1, 2], [3, 4]]) inverse = inv(matrix) print(inverse)
Complexity: O(n^3) time, O(n^2) space
Time Complexity
Matrix inversion typically requires cubic time in the size of the matrix (n x n) due to operations like Gaussian elimination or LU decomposition.
Space Complexity
The algorithm needs space proportional to the matrix size squared to store the matrix and its inverse.
Which Approach is Fastest?
Using numpy's built-in linalg.inv() is optimized and faster than manual methods, especially for large matrices.
| Approach | Time | Space | Best For |
|---|---|---|---|
| numpy.linalg.inv | O(n^3) | O(n^2) | General purpose, large matrices |
| Manual 2x2 calculation | O(1) | O(1) | Small 2x2 matrices, learning |
| scipy.linalg.inv | O(n^3) | O(n^2) | Scientific computing with scipy ecosystem |