Hướng dẫn cofactor matrix python

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:

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:

  • Finding the determinant of a given matrix.
  • Finding the inverse of a matrix and transposing it.

Example 1: Finding cofactor in the 2D matrix

Python3

import numpy as np

def matrix_cofactor(matrix):

    try:

        determinant = np.linalg.det(matrix)

        if(determinant!=0):

            cofactor = None

            cofactor = np.linalg.inv(matrix).T * determinant

            return cofactor

        else:

            raise Exception("singular matrix")

    except Exception as e:

        print("could not find cofactor matrix due to",e)

print(matrix_cofactor([[1, 2], [3, 4]]))

Output:

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

Example 2: Finding cofactor 3D matrix

Python3

import numpy as np

def matrix_cofactor(matrix):

    try:

        determinant = np.linalg.det(matrix)

        if(determinant!=0):

            cofactor = None

            cofactor = np.linalg.inv(matrix).T * determinant

            return cofactor

        else:

            raise Exception("singular matrix")

    except Exception as e:

        print("could not find cofactor matrix due to",e)

print(matrix_cofactor([[1, 9, 3],

                       [2, 5, 4],

                       [3, 7, 8]]))

Output:

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