.inv()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Jun 5, 2024
Contribute to Docs

The .inv() function inverts a given matrix and returns the inverted matrix. If the inversion fails or the given matrix is not a square matrix, then it raises an LinAlgError. Some of its use cases in the field of statistical analysis include:

  • Linear Regression
  • Multivariate Analysis
  • Bayesian Statistics

Syntax

numpy.linalg.inv(a)
  • a: The matrix to be inverted.

Example

The following example demonstrates the usage of the .inv() function:

import numpy as np
array = np.array([[2., 3.], [1., 4.]])
array2 = np.array([[[2., 3.], [1., 4.]], [[6., 4.], [10., 10.]]])
# The determinant is bigger then zero since the above matrices are non-singular
print("One matrix: ")
print(np.linalg.inv(array))
print("\nTwo matrices: ")
print(np.linalg.inv(array2))

The output for the above code is as follows:

One matrix:
[[ 0.8 -0.6]
[-0.2 0.4]]
Two matrices:
[[[ 0.8 -0.6]
[-0.2 0.4]]
[[ 0.5 -0.2]
[-0.5 0.3]]]

Codebyte Example

Run the following codebyte example of the .inv() function, to better understand its working:

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

Note: The .inv() function raises an LinAlgError when a singular matrix is passed for inversion, as it can’t be inverted.

All contributors

Looking to contribute?

Learn Python:NumPy on Codecademy