Invert A Matrix

Goal

This post aims to show how to invert a matrix using numpy i.e., calculating a inverse matrix $A^{-1}$ from $A$

For example, if we have

$$A = \begin{bmatrix} a & b \\ c & d \end{bmatrix} $$

Then, $A^{-1}$ should meet with

$$A A^{-1} = I = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} $$

Reference:

Library

In [1]:
import numpy as np
from numpy.linalg import inv

Create a matrix

In [2]:
arr = np.array([[1, 2], [3, 4]])
arr
Out[2]:
array([[1, 2],
       [3, 4]])

Invert a matrix

In [3]:
arr_inv = inv(arr)
arr_inv
Out[3]:
array([[-2. ,  1. ],
       [ 1.5, -0.5]])

Check $A A^{-1} = I$

In [4]:
np.dot(arr_inv, arr)
Out[4]:
array([[1.00000000e+00, 0.00000000e+00],
       [2.22044605e-16, 1.00000000e+00]])
In [5]:
np.dot(arr, arr_inv)
Out[5]:
array([[1.0000000e+00, 0.0000000e+00],
       [8.8817842e-16, 1.0000000e+00]])

Comments

Comments powered by Disqus