NumPy Tutorial NumPy Statistics NumPy References

NumPy - linalg.inv() function



The NumPy linalg.inv() function is used to compute the (multiplicative) inverse of a matrix. Given that a as square matrix, it returns the matrix ainv satisfying:

dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])

Syntax

numpy.linalg.inv(a)

Parameters

a Required. Specify the matrix to be inverted.

Return Value

Returns (Multiplicative) inverse of the matrix a.

Exception

Raises LinAlgError exception, if a is not square or inversion fails.

Example: inverse matrix of a matrix

In the example below, linalg.inv() function is used to calculate inverse of the given matrix.

import numpy as np
Arr = np.array([[10,20],[30, 40]])

print("Array is:")
print(Arr)

#calculating inverse matrix
print("\nInverse matrix is:")
print(np.linalg.inv(Arr))

The output of the above code will be:

Array is:
[[10 20]
 [30 40]]

Inverse matrix is:
[[-0.2   0.1 ]
 [ 0.15 -0.05]]

Example: inverse matrix for a stack of matrices

The function can also be used to calculate the inverse matrix for a stack of matrices. Consider the following example.

import numpy as np
Arr = np.array([ [[10, 20], [30, 40]], 
                 [[10, 30], [20, 40]] ])

#calculating inverse matrix
print("\nInverse matrix is:")
print(np.linalg.inv(Arr))

The output of the above code will be:

Inverse matrix is:
[[[-0.2   0.1 ]
  [ 0.15 -0.05]]

 [[-0.2   0.15]
  [ 0.1  -0.05]]]

❮ NumPy - Functions