
- SciPy - Home
- SciPy - Introduction
- SciPy - Environment Setup
- SciPy - Basic Functionality
- SciPy - Relationship with NumPy
- SciPy Clusters
- SciPy - Clusters
- SciPy - Hierarchical Clustering
- SciPy - K-means Clustering
- SciPy - Distance Metrics
- SciPy Constants
- SciPy - Constants
- SciPy - Mathematical Constants
- SciPy - Physical Constants
- SciPy - Unit Conversion
- SciPy - Astronomical Constants
- SciPy - Fourier Transforms
- SciPy - FFTpack
- SciPy - Discrete Fourier Transform (DFT)
- SciPy - Fast Fourier Transform (FFT)
- SciPy Integration Equations
- SciPy - Integrate Module
- SciPy - Single Integration
- SciPy - Double Integration
- SciPy - Triple Integration
- SciPy - Multiple Integration
- SciPy Differential Equations
- SciPy - Differential Equations
- SciPy - Integration of Stochastic Differential Equations
- SciPy - Integration of Ordinary Differential Equations
- SciPy - Discontinuous Functions
- SciPy - Oscillatory Functions
- SciPy - Partial Differential Equations
- SciPy Interpolation
- SciPy - Interpolate
- SciPy - Linear 1-D Interpolation
- SciPy - Polynomial 1-D Interpolation
- SciPy - Spline 1-D Interpolation
- SciPy - Grid Data Multi-Dimensional Interpolation
- SciPy - RBF Multi-Dimensional Interpolation
- SciPy - Polynomial & Spline Interpolation
- SciPy Curve Fitting
- SciPy - Curve Fitting
- SciPy - Linear Curve Fitting
- SciPy - Non-Linear Curve Fitting
- SciPy - Input & Output
- SciPy - Input & Output
- SciPy - Reading & Writing Files
- SciPy - Working with Different File Formats
- SciPy - Efficient Data Storage with HDF5
- SciPy - Data Serialization
- SciPy Linear Algebra
- SciPy - Linalg
- SciPy - Matrix Creation & Basic Operations
- SciPy - Matrix LU Decomposition
- SciPy - Matrix QU Decomposition
- SciPy - Singular Value Decomposition
- SciPy - Cholesky Decomposition
- SciPy - Solving Linear Systems
- SciPy - Eigenvalues & Eigenvectors
- SciPy Image Processing
- SciPy - Ndimage
- SciPy - Reading & Writing Images
- SciPy - Image Transformation
- SciPy - Filtering & Edge Detection
- SciPy - Top Hat Filters
- SciPy - Morphological Filters
- SciPy - Low Pass Filters
- SciPy - High Pass Filters
- SciPy - Bilateral Filter
- SciPy - Median Filter
- SciPy - Non - Linear Filters in Image Processing
- SciPy - High Boost Filter
- SciPy - Laplacian Filter
- SciPy - Morphological Operations
- SciPy - Image Segmentation
- SciPy - Thresholding in Image Segmentation
- SciPy - Region-Based Segmentation
- SciPy - Connected Component Labeling
- SciPy Optimize
- SciPy - Optimize
- SciPy - Special Matrices & Functions
- SciPy - Unconstrained Optimization
- SciPy - Constrained Optimization
- SciPy - Matrix Norms
- SciPy - Sparse Matrix
- SciPy - Frobenius Norm
- SciPy - Spectral Norm
- SciPy Condition Numbers
- SciPy - Condition Numbers
- SciPy - Linear Least Squares
- SciPy - Non-Linear Least Squares
- SciPy - Finding Roots of Scalar Functions
- SciPy - Finding Roots of Multivariate Functions
- SciPy - Signal Processing
- SciPy - Signal Filtering & Smoothing
- SciPy - Short-Time Fourier Transform
- SciPy - Wavelet Transform
- SciPy - Continuous Wavelet Transform
- SciPy - Discrete Wavelet Transform
- SciPy - Wavelet Packet Transform
- SciPy - Multi-Resolution Analysis
- SciPy - Stationary Wavelet Transform
- SciPy - Statistical Functions
- SciPy - Stats
- SciPy - Descriptive Statistics
- SciPy - Continuous Probability Distributions
- SciPy - Discrete Probability Distributions
- SciPy - Statistical Tests & Inference
- SciPy - Generating Random Samples
- SciPy - Kaplan-Meier Estimator Survival Analysis
- SciPy - Cox Proportional Hazards Model Survival Analysis
- SciPy Spatial Data
- SciPy - Spatial
- SciPy - Special Functions
- SciPy - Special Package
- SciPy Advanced Topics
- SciPy - CSGraph
- SciPy - ODR
- SciPy Useful Resources
- SciPy - Reference
- SciPy - Quick Guide
- SciPy - Cheatsheet
- SciPy - Useful Resources
- SciPy - Discussion
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