Inverting a matrix in Python

Meharaj Ul Mahmmud
2 min readApr 23, 2021

Implementing a python script to inverse a 3x3 square matrix.

A matrix is invertible if its determinant is not equated to zero (0). , there are few steps till the final result. We will go through each of them.

Steps to inverse a matrix:

  1. Check the determinant.
  2. If the determinant is non-zero, calculate the cofactor matrix.
  3. Calculate the adjoint matrix.
  4. Multiply the adjoint matrix with 1 over determinant (1 / determinant).

Inverse matrix formula

Inv(A) = (1 / det(A)) * Adj(A)

Let’s find the Inverse of the matrix.

Step 1 — Calculating the determinant

We will have to calculate the cofactor for each of the elements of the first row. If the determinant of the given matrix is zero, then there is no inverse for the given matrix

det (A) = 1(0–24) -2(0–20) + 3(0–5)

det(A) = -24 +40–15

det (A) = 1

Therefore, we can say that the given matrix has an inverse matrix.

Here we have used calcMinor() function, which will return the cofactor value for a certain element.

And the function is implemented this way.

In the calcMinor() function we have used negative indexing. This is pretty basic. But if you get a hard time understanding how the negative indexing is working here, try to visualize the code. It will come to you eventually.

Step 2 — Calculating the cofactor matrix

We will have to calculate the cofactor for each of the elements of the matrix. We will use the calcMinor() function here again.

Step 3 — Calculating the adjoint matrix

Adjoint or Adjugate matrix is basically the transpose of the cofactor matrix. So now we will transpose the matrix we got in the second step.

This function will return us the Adjoint matrix, which is the transpose of the cofactor matrix.

Step 4 — Final step, Multiplying the adjoint matrix with (1 / determinant)

Multiply the adjoint matrix with (1/determinant).

This function will return us the inversed matrix.

To sum it all,

And there you go. You have implemented a python script to compute the inverse of a 3x3 square matrix.

Thanks for your patience.

--

--