0
0
NumpyHow-ToBeginner ยท 3 min read

How to Find Inverse of Matrix Using NumPy in Python

To find the inverse of a matrix in NumPy, use the numpy.linalg.inv() function by passing your square matrix as an argument. This function returns the inverse matrix if it exists; otherwise, it raises an error for singular matrices.
๐Ÿ“

Syntax

The syntax to find the inverse of a matrix using NumPy is:

  • numpy.linalg.inv(a): where a is a square matrix (2D array).
  • The function returns the inverse of matrix a.
  • If the matrix is not invertible (singular), it raises a LinAlgError.
python
import numpy as np

# Syntax to find inverse
inv_matrix = np.linalg.inv(a)
๐Ÿ’ป

Example

This example shows how to create a 2x2 matrix and find its inverse using numpy.linalg.inv(). It also prints the original and inverse matrices.

python
import numpy as np

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

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

print("Original matrix:")
print(matrix)
print("\nInverse matrix:")
print(inverse_matrix)
Output
Original matrix: [[4 7] [2 6]] Inverse matrix: [[ 0.6 -0.7] [-0.2 0.4]]
โš ๏ธ

Common Pitfalls

Common mistakes when finding the inverse of a matrix with NumPy include:

  • Trying to invert a non-square matrix (must be square).
  • Attempting to invert a singular matrix (determinant zero), which causes LinAlgError.
  • Not handling exceptions when the matrix is not invertible.

Always check if the matrix is square and has a non-zero determinant before inversion.

python
import numpy as np

matrix = np.array([[1, 2], [2, 4]])  # Singular matrix

try:
    inv = np.linalg.inv(matrix)
except np.linalg.LinAlgError:
    inv = None
    print("Matrix is singular and cannot be inverted.")
Output
Matrix is singular and cannot be inverted.
๐Ÿ“Š

Quick Reference

FunctionDescription
numpy.linalg.inv(a)Returns the inverse of a square matrix a
numpy.linalg.det(a)Computes the determinant of matrix a (useful to check invertibility)
numpy.linalg.LinAlgErrorError raised if matrix is singular and cannot be inverted
โœ…

Key Takeaways

Use numpy.linalg.inv() to find the inverse of a square matrix.
The matrix must be square and non-singular to have an inverse.
Check the determinant with numpy.linalg.det() before inversion to avoid errors.
Handle exceptions for singular matrices to prevent program crashes.
Inverse calculation is useful for solving linear equations and transformations.