How can SciPy be used to calculate the inverse of a matrix in Python?


Sometimes, it may be required to mathematically compute the inverse of a matrix and use the result of the operation for other purposes. Below are the steps to manually find the inverse of a matrix.

Calculate the value of ‘minors’

In this calculation, the values of current row and column are ignored, and the determinant of the remaining values are found. The calculated minors are stored in a matrix.

The next step is to find the cofactors, wherein the alternate sign of values in the ‘minors’ matrix are changed from ‘+’ to ‘-‘ and vice-versa.

Next, the matrix is transposed, i.e the rows are converted to columns and columns are converted to rows.

The determinant of the original matrix is found, and all the elements in the previously computed matrix is divided by the determinant. The resulting matrix would be the inverse of the original matrix.

Finding the inverse of a matrix manually using calculations is a lengthy process. This is where the ‘inv’ function present in ‘SciPy’ library comes into play.

Syntax of ‘inv’ function

scipy.linalg.inv(matrix)

The ‘matrix’ is the parameter that is passed to the ‘inv’ function to find its inverse value.

Example

 Live Demo

from scipy import linalg
import numpy as np
two_d_matrix = np.array([ [7, 9], [33, 8] ])
print("The inverse of the matrix is :")
print(linalg.inv(two_d_matrix ))

Output

The inverse of the matrix is :
[[-0.03319502 0.0373444 ]
[ 0.13692946 -0.02904564]]

Explanation

  • The required libraries are imported.
  • A matrix is defined with certain values in it.
  • Parameters are passed to the ‘inv’ function that computes the inverse of the matrix.
  • The function is called.
  • This output is displayed on the console.

Updated on: 11-Dec-2020

467 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements