Python program to find the inverse of a Matrix


The inverse of a matrix is another matrix that is when multiplied with the original matrix will produce an identity matrix. It is used to find the unknown variables in the matrix equation.

The inverse matrix is denoted as -1 as superscript in the original matrix name, for example A-1 is the inverse of matrix A.

The following example shows the usage of the inverse of a matrix in a matrix equation.

A x = b

Where A is a mxn matrix x is the nx1 matrix of variables and b is the nx1 matrix of constants.

x = A-1 b

The formula for calculation of inverse of a matrix is given below –

A-1= adj(A)/det(A)

Where det(A) is the determinant of matrix A, adj(A) is the adjugate matrix which is the transpose of its cofactor matrix.

Note: – If the determinant of a matrix is zero then its inverse does not exist.

In this article, you will see a python program that calculates the inverse of a given matrix.

Python program to find the inverse of a matrix

Some examples of finding the inverse of a matrix using Python code are given below. We will use the built-in function given in linalg module of NumPy package of Python language.

Example 1:

# Python program to find the inverse of a matrix

import numpy as np

# Taking a 3 x 3 matrix
A = np.array([[4, -2, 1],
	     [5, 0, 3],
	     [-1, 2, 6]])

# find the inverse of the matrix
try:
    print("The inverse of Matrix A is:\n")
    print(np.linalg.inv(A))
except:
    print("Inverse doesn't exsit!")

When you execute this program it will display the given output in your terminal –

output of the matrix

Example 2:

# Python program to find the inverse of a matrix

import numpy as np

# Taking a 3 x 3 matrix
A = np.array([[4, -2, 1],
	     [5, 0, 3],
	     [0, 0, 0]])

# find the inverse of the matrix
try:
    print(np.linalg.inv(A))
except:
    print("Inverse doesn't exsit!")

In this example, the determinant of this matrix is 0 so inverse doesn’t exist. You can see the output of this command in the given image.

inverse output

Example: 3

# Python program to find the inverse of a matrix

import numpy as np

# Taking a 4 x 4 matrix
A = np.array([[4, -2, 1, 2],
	     [5, 0, 3, 5],
	     [0, 7, 1, 9],
             [1, 8, 7, 3]])

# find the inverse of the matrix
try:
    print(np.linalg.inv(A))
except:
    print("Inverse doesn't exsit!")

On executing this program you will see the inverse of matrix A –

inverse of matrix A

Conclusion

So now I hope this article gives you a basic understanding of how to find the inverse of a matrix and implement it using the Python program.

Now if you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.