pythonloopspython-3.xfor-looprecursion

Recursive Matrix determinant function?


def determinant(M):
    """
    Finds the determinant of matrix M.
    """
    if dimension(M)[0]!=dimension(M)[1]:
        print("This matrix is not a square matrix and therefore cannot have a determinant!")
        return
    elif dimension(M)[0]==dimension(M)[1]:
        if dimension(M)==(2,2):
            return (M[0][0]*M[1][1])-(M[0][1]*M[1][0])
        else:
            return (M[0][0]*determinant(reduce_matrix(M,1,1))) - (M[0][1]*determinant(reduce_matrix(M,1,2))) + (M[0][2]*determinant(reduce_matrix(M,1,3)))

EDIT: This code here is capable of finding the determinant of 3x3 matrices, but ONLY 3x3 matrices. How can I edit this in order to find the determinant of ANY size square matrix?


Solution

  • You can use list comprehensions to apply an expression by an input list like so:

    [n ** 2 for n in [1, 2, 3]] == [1, 4, 9]
    

    I assume you'd like to accumulate the results, in which case you can use the sum function.

    sum([1, 2, 3]) == 6
    

    By applying both you end up with an expression like this:

    sum([((-1) ** i) * (M[0][i] * determinant(reduce_matrix(M, 1, i + 1))) for i in range(0, dimension(M)[1])])
    

    Note that range excludes the last element.

    Also be cautious of operator precedence:

    -1 ** 2 != (-1) ** 2