将numpy数组转换为稀疏矩阵求逆,然后再转换回numpy数组

2024-10-01 19:19:47 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的函数中,如果我使用 np.linalg.invNxNt变大时,函数似乎要花很长时间。在我的头脑中,我知道我应该使用稀疏矩阵,它在scipy中(我以前从未使用过),但是我真的很难将M转换为稀疏矩阵,找到它的逆矩阵,然后将它转换回for循环的numpy数组。在

如果有人能帮忙,我会非常感激的!谢谢!在

def BTCS(phiOld, c, Nx, Nt):

#Initiate phi for the for loop
phi = phiOld.copy()

#Crate the matrix M for the BTCS scheme
M = np.zeros((Nx, Nx))

for i in range(Nx):
    M[i,(i-1)%Nx] = -c/2
    M[i,i] = 1
    M[i,(i+1)%Nx] = c/2

#Take the inverse of M so as to have phi(n+1) = M^(-1) * phi(n)
M_inv = np.linalg.inv(M)

#Loop over all time steps
for it in range(Nt):
    #Loop over space (excluding end points)
    for ix in range(1,Nx-1):
        phi[ix] = M_inv.dot(phiOld)[ix]
    #Compute boundary values using periodic boundary conditions
    phi[0] = M_inv.dot(phiOld)[0]
    phi[Nx-1] = phi[0]

    #Update old time value
    phiOld = phi.copy()

return phi

Tags: the函数infornprange矩阵ix

热门问题