Python Numpy.linalg.inv() - Inverse Matrix

Jinku Hu Jan 30, 2023

`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.

Author: Jinku Hu

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.