scipy.linalg.inv() Function



The function linalg.inv() is part of SciPy.Linalg Package. This function takes an input matrix and returns its inverse. SciPy, short for Scientist Python, utilizes NumPy arrays for fundamental operations. The Linear Algebra module is used for performing various operations on matrices of variable sizes. This module includes all the features of the Linear Algebra module in NumPy, along with some additional functionalities.

Syntax

The syntax of the SciPy.linalg.inv() function is as follows −

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

Parameters

The following is a list of parameters accepted by the above function −

  • a − This parameter accepts an array as input, representing a square matrix that needs to be inverted.

  • overwrite_a() − This parameter accepts a Boolean data type that discards data in the input matrix to improve performance. The default value is False.

  • check_finite() − This parameter accepts a Boolean data type that checks whether the input matrix contains only finite numbers. Disabling this parameter improves performance, but if the input matrix contains infinities or NaNs, it may lead to problems such as crashes or non-termination. The default value is True.

Return Value

The linalg.inv() function takes the above parameters and returns the inverse matrix of the input matrix(a).

Example:1

In the following example code, we use the linalg module, which is imported from the SciPy package. The input is a square matrix declared using arrays in the NumPy module. When the matrix is passed as parameter to linalg.inv(), it returns the inverse matrix of the given number.

from scipy import linalg
import numpy as np
a = np.array([[1., 2.], [3., 4.]])
result = linalg.inv(a)
print(result)

The result is obtained as follows −

array([[-2. ,  1. ],
       [ 1.5, -0.5]])

Example:2

In the example code below, we set the check_finite parameter to False, which can result in unexpected output, crashes, non-termination. The code imports SciPy and NumPy, creates a matrix with a NaN, and attempts to invert it without checking for finite numbers.

from scipy import linalg
import numpy as np
a = np.array([[1., 2.], [3., np.nan]])
result = linalg.inv(a, check_finite=False)
print(result)

We will get the output as follows −

array([[nan, nan],
       [nan, nan]])

Example:3

In the following example code, we include all the parameters for the linalg.inv() function. The code imports SciPy and NumPy, creates a 2*2 matrix, and inverts it while preserving the original matrix and checking for finite values.

from scipy import linalg
import numpy as np
a = np.array([[1., 2.], [3., 4.]])
result = linalg.inv(a, overwrite_a=False, check_finite=True)
print(result)

The result is obtained as follows −

array([[-2. ,  1. ],
       [ 1.5, -0.5]])
parent_file.htm
Advertisements