0
0
PythonProgramBeginner · 2 min read

Python Program to Find Inverse of Matrix

You can find the inverse of a matrix in Python using numpy.linalg.inv() function like this: import numpy as np; inv_matrix = np.linalg.inv(matrix).
📋

Examples

Input[[1, 2], [3, 4]]
Output[[-2. 1. ] [ 1.5 -0.5]]
Input[[4, 7], [2, 6]]
Output[[ 0.6 -0.7] [-0.2 0.4]]
Input[[1, 2], [2, 4]]
OutputMatrix is singular and cannot be inverted.
🧠

How to Think About It

To find the inverse of a matrix, first check if the matrix is square and non-singular (its determinant is not zero). Then use a mathematical method or a library function to calculate the inverse matrix, which when multiplied by the original matrix gives the identity matrix.
📐

Algorithm

1
Get the input matrix.
2
Check if the matrix is square (same number of rows and columns).
3
Calculate the determinant of the matrix.
4
If determinant is zero, report that the matrix cannot be inverted.
5
Otherwise, compute the inverse using a matrix inversion method.
6
Return or print the inverse matrix.
💻

Code

python
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)
Output
[[-2. 1. ] [ 1.5 -0.5]]
🔍

Dry Run

Let's trace the example matrix [[1, 2], [3, 4]] through the code

1

Input matrix

matrix = [[1, 2], [3, 4]]

2

Call np.linalg.inv

Calculate inverse of matrix

3

Compute inverse

Inverse matrix = [[-2.0, 1.0], [1.5, -0.5]]

4

Return result

Return the inverse matrix

StepOperationResult
1Input matrix[[1, 2], [3, 4]]
2Calculate inverse[[-2.0, 1.0], [1.5, -0.5]]
3Return 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

Manual calculation using adjoint and determinant
python
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))
This method works only for 2x2 matrices and is less flexible than numpy but good for learning.
Using scipy.linalg.inv
python
from scipy.linalg import inv
import numpy as np

matrix = np.array([[1, 2], [3, 4]])
inverse = inv(matrix)
print(inverse)
Scipy's inv function is similar to numpy's but part of a larger scientific library.

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.

ApproachTimeSpaceBest For
numpy.linalg.invO(n^3)O(n^2)General purpose, large matrices
Manual 2x2 calculationO(1)O(1)Small 2x2 matrices, learning
scipy.linalg.invO(n^3)O(n^2)Scientific computing with scipy ecosystem
💡
Always check if the matrix is square and non-singular before trying to find its inverse.
⚠️
Trying to invert a non-square or singular matrix without checking causes errors or incorrect results.