What is scipy.linalg.inv() in Python?

SciPy is a strong open-source Python toolkit that provides a variety of scientific computing features. It extends the NumPy library to help with scientific and technical computing tasks.

The scipy.linalg module focuses on linear algebra operations. It is an essential tool for solving systems of linear equations and transformations and finds applications in diverse fields such as machine learning.

The scipy.linalg.inv() Function

The scipy.linalg.inv() function is used to calculate the inverse of a given square matrix A. The inverse of a matrix AA is denoted as A1A^{-1} and is defined as the matrix that gives the identity matrix, II when multiplied with AA.

The inverse of a matrix AA is calculated as follows:

Syntax

Here you can see the basic syntax for the scipy.linalg.inv() function:

scipy.linalg.inv(a)
Syntax for scipy.linalg.inv() function
  • a is a required parameter representing the input square matrix for which the inverse needs to be computed.

Note: Make sure you have the SciPy library installed. To learn more about the SciPy installation on your system, click here.

Code

Let's demonstrate the use of the function scipy.linalg.inv() in the code given below:

import numpy as np
from scipy.linalg import inv
#Defining a square matrix
A = np.array([[2, 1], [4, 3]])
#Computing the inverse of the matrix
A_inv = inv(A)
print("Inverse of matrix A:")
print(A_inv)

Code explanation

  • Line 1–2: Firstly, we import the necessary modules. The numpy module and scipy.linalg.inv from SciPy to calculate the inverse of matrices.

  • Line 5: Next, we define a 2×22\times2 square matrix A using numpy.

  • Line 8: Then, we compute the inverse of A using the inv(A) function and store the result in the variable A_inv.

  • Line 10–11: Finally, we print the inverse of the square matrix A on the console.

Output

Upon execution, the code will use the function scipy.linalg.inv() and compute the inverse of the matrix AA.

The output of the code looks like this:

We learned above that multiplying matrix AA with its inverse A1A^{-1} should give the identity matrix. Let’s confirm this in the code below:

identity_matrix = np.dot(A, A_inv)
print(identity_matrix)

The output:

The expected output of the product of matrix AA and its inverse is the identity matrix. We verified that the scipy.linalg.inv() function has calculated the inverse of the matrix AA successfully.

Note: For in-depth understanding of how to calculate the inverse of a matrix, click here.

Conclusion

Hence, the scipy.linalg.inv() method in Python is useful for computing the inverse of square matrices. It is essential in many scientific and technical applications, including solving linear equations and mathematical problems in linear algebra. SciPy's linear algebra features, especially the inv() function, make it ideal for executing complex scientific computations.



Free Resources

Copyright ©2025 Educative, Inc. All rights reserved