Code to solve determinant using Python without using scipy.linalg.det

theAngryPhysicist picture theAngryPhysicist · Sep 29, 2010 · Viewed 11.9k times · Source

Description(this is a hwk question):

I am not sure where to start here. I plan to use Laplace's Expansion but I am not sure how to implement it for nxn matrices. Any help would be appreciated.

Note: I already have a function to generate random matrices for a nxn matrix. Also the timing the calculation isn't a problem. The only thing I have an issue is how to calculate the determinant.

Had to delete the question description b/c of my class policy.

Answer

stackPusher picture stackPusher · Oct 5, 2016

Here is recursive python code for the adjucate method for finding a matrix's determinant.

def getMatrixMinor(m,i,j):
    return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]

def getMatrixDeternminant(m):
    #base case for 2x2 matrix
    if len(m) == 2:
        return m[0][0]*m[1][1]-m[0][1]*m[1][0]

    determinant = 0
    for c in range(len(m)):
        determinant += ((-1)**c)*m[0][c]*getMatrixDeternminant(getMatrixMinor(m,0,c))
    return determinant

Note that the input is an array of arrays representing the nxn matrix