Skip to content
Related Articles

Related Articles

Improve Article

How to Find cofactor of a matrix using Numpy

  • Last Updated : 14 Sep, 2021

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:

Steps Needed:

Example 1: Finding cofactor in the 2D matrix

Python3




# code to find the cofactor of given matrix
import numpy as np
  
def matrix_cofactor(matrix):
  
    cofactor = None
    cofactor = np.linalg.inv(matrix).T * np.linalg.det(matrix)
  
    # return cofactor matrix of the given matrix
    return cofactor
  
print(matrix_cofactor([[1, 2], [3, 4]]))

Output:

[[ 4. -3.]
 [-2.  1.]]

Example 2: Finding cofactor 3D matrix

Python3




# code to find the cofactor of given matrix
import numpy as np
  
def matrix_cofactor(matrix):
  
    cofactor = None
    cofactor = np.linalg.inv(matrix).T * np.linalg.det(matrix)
  
    # return cofactor matrix of the given matrix
    return cofactor
  
print(matrix_cofactor([[1, 9, 3],
                       [2, 5, 4],
                       [3, 7, 8]]))

Output:

[[ 12.  -4.  -1.]
 [-51.  -1.  20.]
 [ 21.   2. -13.]]



My Personal Notes arrow_drop_up
Recommended Articles
Page :