Finding inverse of a square matrix using SciPy library


SciPy library has scipy.linalg.inv() function for finding the inverse of a square matrix. Let’s understand how we can use this function to calculate the inverse of a matrix −

Example

Inverse of a 2 by 2 matrix

#Importing the scipy package
import scipy.linalg

#Importing the numpy package
import numpy as np

#Declaring the numpy array (Square Matrix)
A = np.array([[3, 3.5],[3.2, 3.6]])

#Passing the values to scipy.linalg.inv() function
M = scipy.linalg.inv(A)

#Printing the result
print('Inverse of 
{}
is {}'.format(A,M))

Output

Inverse of
[[3. 3.5]
[3.2 3.6]]
is [[-9. 8.75]
[ 8. -7.5 ]]

Example

Inverse of a 3 by 3 matrix

import scipy
import numpy as np
A = np.array([[2,1,-2],[1,0,0],[0,1,0]])
M = scipy.linalg.inv(A)
print('Inverse of 
{}
is {}'.format(A,M))

Output

Inverse of
[[ 2 1 -2]
[ 1 0 0]
[ 0 1 0]]
is [[ 0. 1. 0. ]
[ 0. -0. 1. ]
[-0.5 1. 0.5]]

Updated on: 24-Nov-2021

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements