How to Find cofactor of a matrix using Numpy
In this article, we are going to see how to find the cofactor of a given matrix using NumPy. There is no direct way to find the cofactor of a given matrix using Numpy.
Deriving the formula to find cofactor using the inverse of matrix in Numpy
Formula to find the inverse of a matrix:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
A-1 = ( 1 / det(A) )* Adj(A) ----(1)
Adj(A) is the Adjoint matrix of A which can be found by taking the Transpose of the cofactor matrix of A:
Adj(A) = (cofactor(A))T ----(2)
Substituting equation 2 in equation 1 we get the following:
A-1 = ( 1/det(A) ) * (cofactor(A))T
Sending det(A) to another side of the equation:
det(A) * A-1 = (cofactor(A))T
Removing transpose on the Right-hand side(RHS) of the equation will result in applying transpose on the Left-hand side(LHS) of the equation. We can apply transpose after multiplying A-1 by det(A) but for simplicity, we will apply transpose to A-1 then multiply by det(A), however, both results are the same.
det(A) * (A-1)T = cofactor(A)
Finally, we derived the formula to find the cofactor of a matrix:
cofactor(A) = (A-1)T * det(A)
Implementation in Numpy:
Example 1: Finding cofactor in the 2D matrix
[[ 4. -3.] [-2. 1.]]
Example 2: Finding cofactor 3D matrix
[[ 12. -4. -1.] [-51. -1. 20.] [ 21. 2. -13.]]