The Wayback Machine - https://web.archive.org/web/20241001075854/https://www.geeksforgeeks.org/compute-the-inverse-of-a-matrix-using-numpy/
Open In App

Compute the inverse of a matrix using NumPy

Last Updated : 26 Feb, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The inverse of a matrix is just a reciprocal of the matrix as we do in normal arithmetic for a single number which is used to solve the equations to find the value of unknown variables. The inverse of a matrix is that matrix which when multiplied with the original matrix will give as an identity matrix. The inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Using determinant and adjoint, we can easily find the inverse of a square matrix using below formula,

if det(A) != 0
    A-1 = adj(A)/det(A)
else
    "Inverse doesn't exist"  

Matrix Equation

Ax = B\\ =>A^{-1}Ax = A^{-1}B\\ =>x = A^{-1}B

where,

A-1: The inverse of matrix A

x: The unknown variable column

B: The solution matrix

We can find out the inverse of any square matrix with the function numpy.linalg.inv(array). 

Syntax: numpy.linalg.inv(a)

Parameters:

a: Matrix to be inverted

Returns: Inverse of the matrix a.

Example 1:

Python3

# Importing Library
import numpy as np
  
# Finding an inverse of given array
arr = np.array([[1, 2], [5, 6]])
inverse_array = np.linalg.inv(arr)
print("Inverse array is ")
print(inverse_array)
print()
  
# inverse of 3X3 matrix
arr = np.array([[1, 2, 3], 
                [4, 9, 6], 
                [7, 8, 9]])
  
inverse_array = np.linalg.inv(arr)
print("Inverse array is ")
print(inverse_array)
print()
  
# inverse of 4X4 matrix
arr = np.array([[1, 2, 3, 4], 
                [10, 11, 14, 25],
                [20, 8, 7, 55], 
                [40, 41, 42, 43]])
  
inverse_array = np.linalg.inv(arr)
print("Inverse array is ")
print(inverse_array)
print()
  
# inverse of 1X1 matrix
arr = np.array([[1]])
inverse_array = np.linalg.inv(arr)
print("Inverse array is ")
print(inverse_array)

                    

Output:

Inverse array is 
[[-1.5   0.5 ]
 [ 1.25 -0.25]]

Inverse array is 
[[-0.6875     -0.125       0.3125    ]
 [-0.125       0.25       -0.125     ]
 [ 0.64583333 -0.125      -0.02083333]]

Inverse array is 
[[-15.07692308   4.9         -0.8         -0.42307692]
 [ 32.48717949 -10.9          1.8          1.01282051]
 [-20.84615385   7.1         -1.2         -0.65384615]
 [  3.41025641  -1.1          0.2          0.08974359]]

Inverse array is 
[[1.]]

Example 2:

Python3

# Import required package 
import numpy as np 
    
# Inverses of several matrices can 
# be computed at once 
A = np.array([[[1., 2.], [3., 4.]], 
              [[1, 3], [3, 5]]]) 
    
# Calculating the inverse of the matrix 
print(np.linalg.inv(A))

                    

Output:

[[[-2.    1.  ]
  [ 1.5  -0.5 ]]

 [[-1.25  0.75]
  [ 0.75 -0.25]]]


Previous Article
Next Article

Similar Reads

How to Compute the Inverse Cosine and Inverse Hyperbolic Cosine in PyTorch
In this article, we will see how to compute the inverse Cosine and Inverse Hyperbolic Cosine in Pytorch. torch.acos() torch.acos() is used to find the inverse cosine of elements in a given tensor. We can apply this function on real as well as complex tensors. Syntax: torch.acos(input_tensor) Parameter: It will take a tensor which can be real or com
3 min read
Compute the inverse sine with scimath using NumPy in Python
In this article, we will cover how to compute the inverse sine with scimath in Python. np.emath.arcsin method A NumPy array can be created in different ways like, by various numbers, and by defining the size of the Array. It can also be created with the use of various data types such as lists, tuples, etc. NumPy method np.emath.arcsin() method from
2 min read
How to compute the inverse of a square matrix in PyTorch
In this article, we are going to cover how to compute the inverse of a square matrix in PyTorch. torch.linalg.inv() method we can compute the inverse of the matrix by using torch.linalg.inv() method. It accepts a square matrix and a batch of the square matrices as input. If the input is a batch of the square matrices then the output will also have
2 min read
How to inverse a matrix using NumPy
In this article, we will see NumPy Inverse Matrix in Python before that we will try to understand the concept of it. The inverse of a matrix is just a reciprocal of the matrix as we do in normal arithmetic for a single number which is used to solve the equations to find the value of unknown variables. The inverse of a matrix is that matrix which wh
3 min read
Compute the condition number of a given matrix using NumPy
In this article, we will use the cond() function of the NumPy package to calculate the condition number of a given matrix. cond() is a function of linear algebra module in NumPy package. Syntax: numpy.linalg.cond(x, p=None) Example 1: Condition Number of 2X2 matrix C/C++ Code # Importing library import numpy as np # Creating a 2X2 matrix matrix = n
2 min read
Compute the inverse cosine with scimath in Python
In this article, we will compute the inverse cosine with scimath in Python using NumPy. numpy.arccos method A NumPy array can be created in different ways like, by various numbers, and by defining the size of the Array. It can also be created with the use of various data types such as lists, tuples, etc. The np.emath.arccos() method from the NumPy
2 min read
Compute the inverse hyperbolic tangent in Python
In this article, we will cover how to compute the inverse hyperbolic tangent in Python using NumPy. numpy.emath.arctanh methodThe inverse hyperbolic tangent is also called as arctanh or tanh-1. To compute the inverse hyperbolic tangent Python provides a method called arctanh which is present in numpy.emath package. arctanh method accepts an array o
2 min read
How to compute the inverse hyperbolic sine in PyTorch?
In this article, we are going to discuss how to compute the inverse hyperbolic sine in PyTorch. torch.asinh() method: The torch.asinh() method is used to compute the inverse hyperbolic sine of each element present in a given input tensor. This method accepts both real and complex-valued as input. It supports input tensors of any dimension. This met
3 min read
Compute the covariance matrix of two given NumPy arrays
In NumPy for computing the covariance matrix of two given arrays with help of numpy.cov(). In this, we will pass the two arrays and it will return the covariance matrix of two given arrays. Syntax: numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None) Example 1: Python Code import numpy as np array1 = np.array([0, 1
2 min read
Compute the natural logarithm of one plus each element in floating-point accuracy Using NumPy
Let's see the program for computing the natural logarithm of one plus each element of a given array in floating-point accuracy using NumPy library. For doing this task we are using numpy.log1p() function of NumPy. This function returns the array of natural logarithm of one plus each element of the input array. Syntax: numpy.log1p(arr, out = None, *
1 min read
How to compute natural, base 10, and base 2 logarithm for all elements in a given array using NumPy?
numpy.log( ) function in Python returns natural logarithmic of the input where the natural logarithm of a number is its logarithm to the base of the mathematical constant e, where e is an irrational and transcendental number approximately equal to 2.718281828459. Syntax: numpy.log(arr,out) Parameters: arr : Input Value. Can be scalar and numpy ndim
2 min read
Compute the outer product of two given vectors using NumPy in Python
In Python, we can use the outer() function of the NumPy package to find the outer product of two matrices. Syntax : numpy.outer(a, b, out = None) Parameters : a : [array_like] First input vector. Input is flattened if not already 1-dimensional. b : [array_like] Second input vector. Input is flattened if not already 1-dimensional. out : [ndarray, op
3 min read
Compute the determinant of a given square array using NumPy in Python
In Python, the determinant of a square array can be easily calculated using the NumPy package. This package is used to perform mathematical calculations on single and multi-dimensional arrays. numpy.linalg is an important module of NumPy package which is used for linear algebra. We can use det() function of numpy.linalg module to find out the deter
2 min read
Compute the inner product of vectors for 1-D arrays using NumPy in Python
Python has a popular package called NumPy which used to perform complex calculations on 1-D and multi-dimensional arrays. To find the inner product of two arrays, we can use the inner() function of the NumPy package. Syntax: numpy.inner(array1, array2) Parameters: array1, array2: arrays to be evaluated Returns: Inner Product of two arrays Example 1
2 min read
Compute the inner product of vectors for 1-D arrays using NumPy in Python
Python has a popular package called NumPy which used to perform complex calculations on 1-D and multi-dimensional arrays. To find the inner product of two arrays, we can use the inner() function of the NumPy package. Syntax: numpy.inner(array1, array2) Parameters: array1, array2: arrays to be evaluated Returns: Inner Product of two arrays Example 1
2 min read
Compute the factor of a given array by Singular Value Decomposition using NumPy
Singular Value Decomposition means when arr is a 2D array, it is factorized as u and vh, where u and vh are 2D unitary arrays and s is a 1D array of a’s singular values. numpy.linalg.svd() function is used to compute the factor of an array by Singular Value Decomposition. Syntax : numpy.linalg.svd(a, full_matrices=True, compute_uv=True, hermitian=F
2 min read
How to compute the eigenvalues and right eigenvectors of a given square array using NumPY?
In this article, we will discuss how to compute the eigenvalues and right eigenvectors of a given square array using NumPy library. Example: Suppose we have a matrix as: [[1,2], [2,3]] Eigenvalue we get from this matrix or square array is: [-0.23606798 4.23606798] Eigenvectors of this matrix are: [[-0.85065081 -0.52573111], [ 0.52573111 -0.85065081
2 min read
Compute the histogram of a set of data using NumPy in Python
Numpy provides us the feature to compute the Histogram for the given data set using NumPy.histogram() function. The formation of histogram depends on the data set, whether it is predefined or randomly generated. Syntax : numpy.histogram(data, bins=10, range=None, normed=None, weights=None, density=None) Case 1: Computing the Numpy Histogram with th
2 min read
Compute the histogram of nums against the bins using NumPy
In this article, we are going to discuss how to compute the nums against the bins using the NumPy module. A histogram is the best way to visualize the frequency distribution of a dataset by splitting it into small equal-sized intervals called bins. The Numpy histogram function is similar to the hist() function of matplotlib library, the only differ
4 min read
How to compute derivative using Numpy?
In this article, we will learn how to compute derivatives using NumPy. Generally, NumPy does not provide any robust function to compute the derivatives of different polynomials. However, NumPy can compute the special cases of one-dimensional polynomials using the functions numpy.poly1d() and deriv(). Functions used:poly1d(): It helps to define a po
2 min read
Compute the roots of a Chebyshev series with given complex roots using NumPy in Python
In this article, we will see how to compute the roots of a Chebyshev series with given complex roots using NumPy in python. chebyshev.chebroots() method The chebyshev.chebroots() in python that is available in the NumPy module is used to compute the roots of a Chebyshev series with given complex roots in python. The root estimates are obtained as t
2 min read
Compute the roots of a Chebyshev series using NumPy in Python
This article will discuss how to compute the roots of a Chebyshev series in NumPy using Python. Chebyshev polynomials are important in approximation theory these are never formally generated. Only the coefficients are required for all calculations. If we want to compute the roots of a polynomial we have to use the chebyshev.chebroots() method in Nu
2 min read
Compute the Roots of a Hermite_e series with given Complex Roots using NumPy in Python
In this article, we are going to see how to compute the roots of a Hermite_e series with given complex roots in Python. NumPy hermeroots() Methods We use the hermite e.hermeroots() function in Python Numpy to get the roots of a Hermite e series. This function will return an array containing the series' roots. If from all the roots present, all root
2 min read
How to compute the cross product of two given vectors using NumPy?
Let's see the program to compute the cross product of two given vectors using NumPy. For finding the cross product of two given vectors we are using numpy.cross() function of NumPy library. Syntax: numpy.cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)[ Return: cross product of two (arrays of) vectors. Let's see the examples: Example 1: Cross p
1 min read
Compute the mean, standard deviation, and variance of a given NumPy array
In NumPy, we can compute the mean, standard deviation, and variance of a given array along the second axis by two approaches first is by using inbuilt functions and second is by the formulas of the mean, standard deviation, and variance. Method 1: Using numpy.mean(), numpy.std(), numpy.var() Python Code import numpy as np # Original array array = n
2 min read
Compute pearson product-moment correlation coefficients of two given NumPy arrays
In NumPy, We can compute pearson product-moment correlation coefficients of two given arrays with the help of numpy.corrcoef() function. In this function, we will pass arrays as a parameter and it will return the pearson product-moment correlation coefficients of two given arrays. Syntax: numpy.corrcoef(x, y=None, rowvar=True, bias=, ddof=) Return:
1 min read
Compute the weighted average of a given NumPy array
In NumPy, we can compute the weighted of a given array by two approaches first approaches is with the help of numpy.average() function in which we pass the weight array in the parameter. And the second approach is by the mathematical computation first we divide the weight array sum from weight array then multiply with the given array to compute the
2 min read
Compute the median of the flattened NumPy array
In this article, we will discuss how to compute the median of the flattened array. Median is basically that value that separates the lower half of the array with the higher half of array. Example: If there are odd numbers in an array. A = [1,2,3,4,5,6,7] Then the median element will be 7+1/2= 4th element of the array. Hence the Median in this array
2 min read
Compute the Kronecker product of two multidimension NumPy arrays
Given an m X n matrix A and a p X q matrix B, their Kronecker product is A ⊗ B, also called their matrix direct product, is an (m*p) X (n*q) matrix. A = | (a00)  (a01) |  | (a10)  (a11) | B = | (b00)  (b01) |  | (b10)  (b11) | A ⊗ B = | (a00)*(b00)  (a00)*(b01)  (a01)*(b00)  (a01)*(b00) |         | (a00)*(b01)  (a00)*(b11)  (a01)*(b01)  (a01)*(b11)
2 min read
How to compute numerical negative value for all elements in a given NumPy array?
In this article, we will see how to compute the negative value for all elements in a given NumPy array. So, The negative value is actually the number which when added to any number becomes 0. Example: If we take a number as 4 then -4 is its negative number because when we add -4 to 4 we get sum as 0. Now let us take another example, Suppose we take
2 min read
Practice Tags :