Python Numpy.linalg.inv() - Inverse Matrix

  1. Syntax of numpy.linalg.inv()
  2. Example Codes: numpy.linalg.inv() method
  3. Example Codes: numpy.linalg.inv() method with matrix input
  4. Example Codes: numpy.linalg.inv() with matrix array

Numpy.linalg.inv() computes the inverse of the given matrix.

Syntax of numpy.linalg.inv()

numpy.linalg.inverse(arr) 

Parameters

arr input array

Return

It returns the inverse of the given matrix.

It raises the error if the given matrix is not square or inversion fails.

Example Codes: numpy.linalg.inv() method

import numpy as np

arr = np.array([[1, 3], [5, 7]])

arr_inv = np.linalg.inv(arr)

print(arr_inv)

Output:

[[-0.875  0.375]
 [ 0.625 -0.125]]

Example Codes: numpy.linalg.inv() method with matrix input

If the given input is a numpy matrix, then inv() also returns a matrix.

import numpy as np

arr = np.matrix([[1, 3], [5, 7]])

arr_inv = np.linalg.inv(arr)

print(arr_inv, type(arr_inv))

Output:

[[-0.875  0.375]
 [ 0.625 -0.125]] <class 'numpy.matrix'>

Example Codes: numpy.linalg.inv() with matrix array

import numpy as np

arr = np.array([
                [[1, 3],
                 [5, 7]],
                [[2, 5],
                 [4, 6]]])

arr_inv = np.linalg.inv(arr)

print(arr_inv)

Output:

[[[-0.875  0.375]
  [ 0.625 -0.125]]

 [[-0.75   0.625]
  [ 0.5   -0.25 ]]]

If the input array consists of multiple matrices, the numpy linalg.inv() method computes the inverse of them at once.

comments powered by Disqus