Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 579
theAngryPhysicist Avatar asked Jan 21 '23 09:01

theAngryPhysicist


1 Answers

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

like image 86
stackPusher Avatar answered Jan 27 '23 13:01

stackPusher