AppDividend
Latest Code Tutorials

# np.linalg.inv: How to Inverse Matrix in Python

In mathematics, the inverse of a matrix is the reciprocal of a number. The Inverse of a Matrix is identical, but we write it A^-1. When we multiply a number by its reciprocal, we get 1.

## Why do we need an Inverse?

We need an inverse of the Matrix because matrices we don’t divide! Thoughtfully, there is no concept of dividing by a matrix. But we can multiply by an inverse to achieve the same thing. So let’s see how to inverse the numpy Matrix in Python.

## np.linalg.inv

The np.linalg.inv() is a numpy library function that computes a matrix’s (multiplicative) inverse. The inverse of a matrix is a reciprocal of a matrix.

To find the inverse of the Matrix in Python, use the np.linalg.inv() method. It is also defined as a matrix formed that gives an identity matrix when multiplied with the original Matrix.

A matrix’s inverse occurs only if it is a non-singular matrix, i.e., the determinant of a matrix should be 0.

### Equation For Getting Inverse Of A Matrix

```A*x= B
A^-1 A*x= A-1 B
x= A-1 B```

Where A^-1: It denotes the inverse of a matrix.

x: It denotes an unknown column.

B: It denotes the solution matrix.

Now, let’s see the procedure for using Numpy to find the inverse of a matrix.

### Syntax

```numpy.linalg.inv(A)
```

### Parameters

A: It denotes the Matrix to be inverted.

### Return Value

The inverse of Matrix A is returned.

### Note

The inv() function raises a LinAlgError if A is not a square matrix because if A is not a square matrix, inversion fails.

### Example

#### Inversion of 4*4 Matrix.

```import numpy as np

A = np.array([[-5, -2, 3, 4],
[3, 1, 2, 7],
[2, 7, -5, 2],
[6, -6, 8, 4]])

print(np.linalg.inv(A))
```

#### Output

```[[-0.19186047  0.1627907  -0.11046512 -0.0377907 ]
[ 0.64534884 -1.09302326  1.09883721  0.71802326]
[ 0.73837209 -1.23255814  1.12209302  0.85755814]
[-0.22093023  0.58139535 -0.43023256 -0.33139535]]```

#### Explanation

Here A matrix was given as input to the function, and after that Inverse of a matrix was returned as the output.

### Calculating inverses of several matrices

```import numpy as np

A = np.array([[[3., 4.], [4., 5.]],
[[6, 7], [7, 9]]])

print(np.linalg.inv(A))
```

#### Output

```[[[-5.   4. ]
[ 4.  -3. ]]

[[ 1.8 -1.4]
[-1.4  1.2]]]```

#### Explanation

Here, we have given several matrices as an input to the function, and after that inverse of a matrix was returned as the output.

That is it for Numpy.linalg.inv() function.