0
0
NumPydata~5 mins

np.linalg.inv() for matrix inverse in NumPy

Choose your learning style9 modes available
Introduction

We use np.linalg.inv() to find the inverse of a square matrix. The inverse helps us solve equations and understand matrix behavior.

When solving systems of linear equations like Ax = b.
When you want to undo a matrix transformation.
When calculating matrix division in linear algebra problems.
When working with data transformations that require reversing effects.
When analyzing models that involve matrix operations.
Syntax
NumPy
np.linalg.inv(matrix)

The input matrix must be a square 2D array (same number of rows and columns).

If the matrix is not invertible (singular), this function will raise an error.

Examples
Calculate the inverse of a 2x2 matrix.
NumPy
import numpy as np
A = np.array([[1, 2], [3, 4]])
inv_A = np.linalg.inv(A)
print(inv_A)
Another example with a different 2x2 matrix.
NumPy
import numpy as np
B = np.array([[4, 7], [2, 6]])
inv_B = np.linalg.inv(B)
print(inv_B)
Inverse of a 3x3 matrix.
NumPy
import numpy as np
C = np.array([[1, 2, 3], [0, 1, 4], [5, 6, 0]])
inv_C = np.linalg.inv(C)
print(inv_C)
Sample Program

This program shows how to find the inverse of a 2x2 matrix and verifies the result by multiplying the matrix with its inverse. The product should be the identity matrix.

NumPy
import numpy as np

# Define a 2x2 matrix
matrix = np.array([[2, 3], [1, 4]])

# Calculate its inverse
inverse_matrix = np.linalg.inv(matrix)

# Print the original and inverse matrices
print("Original matrix:")
print(matrix)
print("\nInverse matrix:")
print(inverse_matrix)

# Verify by multiplying original and inverse (should be identity matrix)
identity = np.dot(matrix, inverse_matrix)
print("\nProduct of original and inverse (Identity matrix):")
print(identity)
OutputSuccess
Important Notes

If the matrix is singular (no inverse), np.linalg.inv() will raise a LinAlgError.

For large matrices, computing the inverse can be slow and unstable; consider other methods like solving linear systems directly.

Summary

np.linalg.inv() finds the inverse of a square matrix.

The matrix must be square and invertible.

Multiplying a matrix by its inverse gives the identity matrix.