Matrix inversion
Recover an inverse when a square matrix is known to be nonsingular.
NumPy · Function
Computes the inverse of a square matrix, returning a result that multiplies with the input to form the identity. It raises LinAlgError when the input is nonsquare or inversion fails.
The function accepts a square matrix, including batches whose final two dimensions are square, and returns an inverse with matching matrix dimensions. The inverse is the array that produces the identity when multiplied with the input in either order; failure to invert raises LinAlgError.
numpy.linalg.inv(a)| Name | Type | Description |
|---|---|---|
a | (..., M, M) array_like | Matrix to be inverted; expected shape (..., M, M). |
ainv (..., M, M) ndarray or matrix: inverse of the matrix a.
import numpy as np
A = np.array([[1.0, 2.0], [3.0, 4.0]])
A_inv = np.linalg.inv(A)
print(np.allclose(A @ A_inv, np.eye(2)))
print(np.allclose(A_inv @ A, np.eye(2)))Computes the inverse and verifies both multiplication orders produce the 2×2 identity matrix.
Recover an inverse when a square matrix is known to be nonsingular.
Process several matrices together when each item occupies the final two axes.
Verify an inversion numerically by checking products against an identity matrix.
The function returns an array ainv such that A @ ainv and ainv @ A equal the identity matrix. Its input must have square final dimensions.
Follow-up: How can you validate the result? Check both multiplication orders against np.eye using np.allclose, while also handling LinAlgError.
The parameter has shape (..., M, M), so the input can represent one square matrix or a stack of square matrices. The returned value has shape (..., M, M).
Follow-up: What shape constraint applies to each item in a batch? Every matrix represented by the final two axes must be M by M.
It raises numpy.linalg.LinAlgError when the input is not square or inversion fails. In particular, a detected singular matrix causes this exception.
Follow-up: What should code do for a singular matrix? Use a try/except around inv or choose a method suited to the problem, such as a solve operation when solving a system.
numpy.linalg.solvenumpy.linalg.pinvnumpy.linalg.detnumpy.linalg.slogdetnumpy.linalg.matrix_power