Speed up python code for computing matrix cofactors

前端 未结 4 1638
庸人自扰
庸人自扰 2021-01-05 00:40

As part of a complex task, I need to compute matrix cofactors. I did this in a straightforward way using this nice code for computing matrix minors. Here is my code:

4条回答
  •  孤街浪徒
    2021-01-05 00:58

    Instead of using the inverse and determinant, I'd suggest using the SVD

    def cofactors(A):
        U,sigma,Vt = np.linalg.svd(A)
        N = len(sigma)
        g = np.tile(sigma,N)
        g[::(N+1)] = 1
        G = np.diag(-(-1)**N*np.product(np.reshape(g,(N,N)),1)) 
        return U @ G @ Vt 
    

提交回复
热议问题