numpy.linalg.inv()



We use numpy.linalg.inv() function to calculate the inverse of a matrix. The inverse of a matrix is such that if it is multiplied by the original matrix, it results in identity matrix.

Example

import numpy as np 

x = np.array([[1,2],[3,4]]) 
y = np.linalg.inv(x) 
print x 
print y 
print np.dot(x,y)

It should produce the following output −

[[1 2]                                                                        
 [3 4]]                                                                       
[[-2.   1. ]                                                                  
 [ 1.5 -0.5]]                                                                 
[[  1.00000000e+00   1.11022302e-16]                                          
 [  0.00000000e+00   1.00000000e+00]]

Example

Let us now create an inverse of matrix A in our example.

import numpy as np 
a = np.array([[1,1,1],[0,2,5],[2,5,-1]]) 

print 'Array a:” 
print a 
ainv = np.linalg.inv(a) 

print 'Inverse of a:' 
print ainv  

print 'Matrix B is:' 
b = np.array([[6],[-4],[27]]) 
print b 

print 'Compute A-1B:' 
x = np.linalg.solve(a,b) 
print x  
# this is the solution to linear equations x = 5, y = 3, z = -2

It will produce the following output −

Array a:
[[ 1 1 1]
 [ 0 2 5]
 [ 2 5 -1]]

Inverse of a:
[[ 1.28571429 -0.28571429 -0.14285714]
 [-0.47619048 0.14285714 0.23809524]
 [ 0.19047619 0.14285714 -0.0952381 ]]

Matrix B is:
[[ 6]
 [-4]
 [27]]

Compute A-1B:
[[ 5.]
 [ 3.]
 [-2.]]

The same result can be obtained by using the function −

x = np.dot(ainv,b)
numpy_linear_algebra.htm
Advertisements