How to calculate the inverse of a matrix in python using numpy ?

Published: April 16, 2019

DMCA.com Protection Status

To calculate the inverse of a matrix in python, a solution is to use the linear algebra numpy method linalg. Example

\begin{equation}
A = \left( \begin{array}{ccc}
1 & 3 & 3 \\
1 & 4 & 3 \\
1 & 3 & 4
\end{array}\right)
\end{equation}

inverse matrix A_inv

\begin{equation}
A^{-1} = \left( \begin{array}{ccc}
7 & -3 & -3 \\
-1 & 1 & 0 \\
-1 & 0 & 1
\end{array}\right)
\end{equation}

>>> import numpy as np
>>> A = np.array(([1,3,3],[1,4,3],[1,3,4]))
>>> A
array([[1, 3, 3],
       [1, 4, 3],
       [1, 3, 4]])
>>> A_inv = np.linalg.inv(A)
>>> A_inv
array([[ 7., -3., -3.],
       [-1.,  1.,  0.],
       [-1.,  0.,  1.]])

Checking:

>>> A_inv.dot(A)
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

References