SciPy - inv() Function



The inverse of a square matrix can be computed by using the scipy.linalg.inv() method. This is often used in solving linear equations or any other mathematical calculations. For this method to work, the input matrix should be square, meaning that it should have an equal number of rows and columns (nn).

If the input matrix is singular, the procedure will raise a LinAlgError because the determinant is zero for the singular matrix. Make sure the matrix is square and non-singular before using this function.

The overwrite_a parameter in this method supports efficient memory usage which can optimize performance. It also checks the matrix contains only valid numbers, neither NaN nor infinity, in order to avoid problems.

Syntax

Following is the syntax of the SciPy inv() method −

.inv(a, overwrite_a=False, check_finite=True)

Parameters

This method accepts the following parameters −

  • a (array_like) − A square matrix to be inverted. Must have dimensions nn.

  • overwrite_a (bool, optional) − If True, the input matrix a may be overwritten during the computation for better performance. Default is False.

  • check_finite (bool, optional) − If True, it checks that the input matrix contains only finite numbers. Performance could be better if False, but invalid inputs - such as NaNs or infinities - might lead to unexpected behavior. True is the default.

Return Value

inv_a: (ndarray) The inverse of the input matrix a.

Example 1

In the code below we have created a 22 matrix and used inv() method to inverse the matrix. Following is the code −

import numpy as np
from scipy.linalg import inv

matrix = np.array([[4, 7], [2, 6]])
inverse_matrix = inv(matrix)
print("Inverse Matrix:\n", inverse_matrix)

When we run the above program, it produces the following result

Inverse Matrix:
 [[ 0.6 -0.7]
 [-0.2  0.4]]

Example 2

A LinAlgError occurs when a singular matrix with a zero determinant cannot be inverted. In the below code we have created a singular matrix to check whether the inv() method works for the singular matrix.

We need to find the determinant to check for singularity; if that is equal to zero then the matrix is singular.

import numpy as np
from scipy.linalg import det, inv

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

# Compute determinant
determinant = det(singular_matrix)
print("Determinant:", determinant)

# Try computing the inverse
try:
    inverse_matrix = inv(singular_matrix)
    print("Inverse Matrix:\n", inverse_matrix)
except np.linalg.LinAlgError:
    print("Error: The matrix is singular and does not have an inverse.")

Following is an output of the above code

Determinant: 0.0
numpy.linalg.LinAlgError: singular matrix

Example 3

Use SciPy's inv() function with the overwrite_a=True parameter to optimize memory usage when inverting matrices.

The function modifies the input matrix in place during computation to save memory, instead of creating a new copy. This can be useful for large matrices where memory usage is a concern.

import numpy as np
from scipy.linalg import inv

matrix = np.array([[3, 2], [3, 4]])
inverse_matrix = inv(matrix, overwrite_a=True)
print("Inverse Matrix:\n", inverse_matrix)

Output of the above code is as follows

Inverse Matrix:
 [[ 0.66666667 -0.33333333]
 [-0.5         0.5       ]]

Example 4

The product of a matrix and its inverse should yield an identity matrix.

In the below example we first create a square matrix, calculate the inverse of the matrix using the inv() method, and compute the dot product of the square and inverse matrix to check the product is an identity matrix. The numpy.allclose() method determines if the resultant matrix is roughly an identity matrix.

import numpy as np
from scipy.linalg import inv

matrix = np.array([[2, 1], [7, 4]])
inverse_matrix = inv(matrix)
identity_matrix = np.dot(matrix, inverse_matrix)

# Check if it is an identity matrix
is_identity = np.allclose(identity_matrix, np.eye(identity_matrix.shape[0]))

print("Identity Matrix:\n", identity_matrix)
print("Is the result an identity matrix?", is_identity)

Output of the above code is as follows

Identity Matrix:
 [[1. 0.]
 [0. 1.]]
Is the result an identity matrix? True
scipy_linalg.htm
Advertisements