# NumPy: Inverse Matrix

In Python, the inverse of a matrix can be calculated importing NumPy linalg.

import numpy as np
from numpy import linalg

A = np.array([[-2, 5], [3, 1]])
B = linalg.inv(A)

print(B)
'''
[[-0.05882353  0.29411765]
[ 0.17647059  0.11764706]]
'''


linalg is often used for vector/matrix calculations and linalg.inv returns the inverse matrix.

## LinAlgError

All matrices don't always have the inverse matrices and inv raises the exception if the matrix doesn't have the inverse.

import numpy as np
from numpy import linalg

A = np.array([[2, 1], [2, 1]])
B = linalg.inv(A)

# numpy.linalg.LinAlgError: Singular matrix


$det(A) = 0$

so A doesn't have an inverse matrix. NumPy is so smart that it calculates the determinant of a matrix exactly.

import numpy as np
from numpy import linalg

A = np.array([[2, 0.5], [4, 1]])
B = linalg.inv(A)

# numpy.linalg.LinAlgError: Singular matrix


The same is true of fractions.

import numpy as np
from numpy import linalg

A = np.array([[2, 1 / 2], [4, 1]])
B = linalg.inv(A)

# numpy.linalg.LinAlgError: Singular matrix


## Dimension error

In algebra, the inverse of a square matrix can not be defined.

import numpy

from numpy import linalg

A = numpy.array([[1, 2, 3], [4, 5, 6]])

B = linalg.inv(A)

print(B)
# numpy.linalg.LinAlgError: Last 2 dimensions of the array must be square


Note: NumPy shape returns the dimension (shape) of a matrix. The shape of A is (2, 3).