Solution: Matrix Determinant#

Write functions that return the determinant of square matrix of orders (\(2\times2\)), (\(3\times3\)), and (\(n\times n\)).

Rules#

  1. Function returns a integer.

  2. You must not use any external function to calculate the determinant.

Function Definition#

import numpy as np

def get_minor_ij(A, i, j):
    M = np.delete(A, i-1, axis=0) # remove a row (axis=0)
    M = np.delete(M, j-1, axis=1) # remove a column (axis=1)

    return M

Order 2#

A = np.array([[ 2, 5],
              [ 1, -3]]
            )

# numpy determinant function:
round(np.linalg.det(A))
-11
def get_determinant_2(A):
  detA = A[0, 0]*A[1, 1] - (A[0, 1]*A[1, 0])
  return detA

get_determinant_2(A)
-11

Order 3#

A = np.array([[ 9, 12, 18],
              [ 2, -2,  5],
              [11,-17, 19]]
            )

# numpy determinant function:
round(np.linalg.det(A))
411
def get_determinant_3(A):

    determinant = 0
    i = 1 # any row will work
    for j in range(3):
        M = get_minor_ij(A, i, j+1)
        detM = get_determinant_2(M)
        determinant += A[i-1, j]*(-1)**(i + j+1)*detM

    return determinant

get_determinant_3(A)
411

Larger Orders: recursive solution#

A = np.array([[5, 2, 1, 4, 6],
              [9, 4, 2, 5, 2],
              [11, 5, 7, 3, 9],
              [5, 6, 6, 7, 2],
              [7, 5, 9, 3, 3]])

# numpy determinant function:
round(np.linalg.det(A))
-2004
def get_determinant_n(A):

    n = A.shape[0]
    m = A.shape[1]

    if n != m:
        return None
    
    i = 1 # any row will work
    if n == 1:
        determinant = A[0][0]
        return determinant
    else:
        determinant = 0
        for b in range(n):
            j = b + 1
            M = get_minor_ij(A, i, j)
            determinant += A[i-1, b]*(-1)**(i + j)*get_determinant_n(M)
        return determinant

get_determinant_n(A)
-2004