computing determinant of a matrix (nxn) recursively

前端 未结 5 1067
心在旅途
心在旅途 2021-01-19 05:26

I\'m about to write some code that computes the determinant of a square matrix (nxn), using the Laplace algorithm (Meaning recursive algorithm) as written Wikipedia\'s Lapla

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-19 05:49

    i posted this code because i couldn't fine it on the internet, how to solve n*n determinant using only standard library. the purpose is to share it with those who will find it useful. i started by calculating the submatrix Ai related to a(0,i). and i used recursive determinant to make it short.

      def submatrix(M, c):
        B = [[1] * len(M) for i in range(len(M))]
    
    
        for l in range(len(M)):
            for k in range(len(M)):
                B[l][k] = M[l][k]
    
        B.pop(0)
    
        for i in range(len(B)):
            B[i].pop(c)
        return B
    
    
    def det(M):
        X = 0
        if len(M) != len(M[0]):
            print('matrice non carrée')
        else:
            if len(M) <= 2:
                return M[0][0] * M[1][1] - M[0][1] * M[1][0]
            else:
                for i in range(len(M)):
                    X = X + ((-1) ** (i)) * M[0][i] * det(submatrix(M, i))
        return X
    

    sorry for not commenting before guys :) if you need any further explanation don't hesitate to ask .

提交回复
热议问题