# NumPy: Inverse of a Matrix

In this tutorial, we will make use of NumPy's numpy.linalg.inv() function to find the inverse of a square matrix.

In Linear Algebra, an identity matrix (or unit matrix) of size $n$ is an $n \times n$ square matrix with $1$'s along the main diagonal and $0$'s elsewhere.

An identity matrix of size $n$ is denoted by $I_{n}$.

$$I_{1} = \begin{bmatrix} 1 \end{bmatrix} , I_{2} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \\ \end{bmatrix} , I_{3} = \begin{bmatrix} 1 & 0 & 0\\ 0 & 1 & 0\\ 0 & 0 & 1 \end{bmatrix} , I_{4} = \begin{bmatrix} 1 & 0 & 0 & 0\\ 0 & 1 & 0 & 0\\ 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 1 \end{bmatrix} , ...$$

An inverse of a square matrix $A$ of order $n$ is the matrix $A^{-1}$ of the same order, such that, their product results in an identity matrix $I_{n}$.

$$AA^{-1} = A^{-1}A = I_{n}$$

An inverse of a matrix is also known as a reciprocal matrix.

Now we pick an example matrix from a Schaum's Outline Series book Theory and Problems of Matrices by Frank Aryes, Jr1.

$$\begin{bmatrix} 1 & 2 & 3 \\ 1 & 3 & 3 \\ 1 & 2 & 4 \end{bmatrix}$$

We will use NumPy's numpy.linalg.inv() function to find its inverse. The NumPy code is as follows.

				
import numpy as np

a = np.array([[1, 2, 3], [1, 3, 3], [1, 2, 4]])
ainv = np.linalg.inv(a)

print(ainv)



Executing the above script, we get the matrix

				
[[ 6.  -2.  -3.]
[-1.   1.   0.]
[-1. 	0. 	 1.]]



which is its inverse. You can verify the result using the numpy.allclose() function. Since the resulting inverse matrix is a $3 \times 3$ matrix, we use the numpy.eye() function to create an identity matrix. If the generated inverse matrix is correct, the output of the below line will be True.

				
print(np.allclose(np.dot(ainv, a), np.eye(3)))