如何在Python的SciPy中更改稀疏矩阵中的元素?

2024-04-23 11:35:53 发布

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

我已经建立了一个小代码,我想用来解决特征值问题涉及大型稀疏矩阵。很好,我现在要做的就是将稀疏矩阵中的一些元素设置为零,即最上面一行的元素(对应于实现边界条件)。我可以调整下面的列向量(C0、C1和C2)来实现这一点。不过,我想知道是否有更直接的方法。显然,NumPy索引不适用于SciPy的稀疏包。

import scipy.sparse as sp
import scipy.sparse.linalg  as la
import numpy as np
import matplotlib.pyplot as plt

#discretize x-axis
N = 11
x = np.linspace(-5,5,N)
print(x)
V = x * x / 2
h = len(x)/(N)
hi2 = 1./(h**2)
#discretize Schroedinger Equation, i.e. build 
#banded matrix from difference equation
C0 = np.ones(N)*30. + V
C1 = np.ones(N) * -16.
C2 = np.ones(N) * 1.
diagonals = np.array([-2,-1,0,1,2])
H = sp.spdiags([C2, C1, C0,C1,C2],[-2,-1,0,1,2], N, N)
H *= hi2 * (- 1./12.) * (- 1. / 2.)
#solve for eigenvalues
EV = la.eigsh(H,return_eigenvectors = False)

#check structure of H
plt.figure()
plt.spy(H)
plt.show()

这是由上面代码构建的矩阵的可视化。我想把第一行的元素设为0。enter image description here


Tags: 代码import元素asnponesplt矩阵
1条回答
网友
1楼 · 发布于 2024-04-23 11:35:53

正如评论中所建议的,我会把我发现的答案贴到我自己的问题上。在SciPy的稀疏包中有几个矩阵类,它们列在here。可以将稀疏矩阵从一个类转换为另一个类。因此,对于我需要做的事情,我选择将稀疏矩阵转换为类csr_矩阵,只需通过

H = sp.csr_matrix(H)

然后,我可以使用常规NumPy符号将第一行中的元素设置为0:

H[0,0] = 0
H[0,1] = 0
H[0,2] = 0

为了完整起见,我在下面发布了完整的修改过的代码片段。

#SciPy Sparse linear algebra takes care of sparse matrix computations
#http://docs.scipy.org/doc/scipy/reference/sparse.linalg.html
import scipy.sparse as sp
import scipy.sparse.linalg  as la

import numpy as np
import matplotlib.pyplot as plt

#discretize x-axis
N = 1100
x = np.linspace(-100,100,N)
V = x * x / 2.
h = len(x)/(N)
hi2 = 1./(h**2)

#discretize Schroedinger Equation, i.e. build 
#banded matrix from difference equation
C0 = np.ones(N)*30. + V
C1 = np.ones(N) * -16.
C2 = np.ones(N) * 1.

H = sp.spdiags([C2, C1, C0, C1, C2],[-2,-1,0,1,2], N, N)
H *= hi2 * (- 1./12.) * (- 1. / 2.)
H = sp.csr_matrix(H)
H[0,0] = 0
H[0,1] = 0
H[0,2] = 0

#check structure of H
plt.figure()
plt.spy(H)
plt.show()

EV = la.eigsh(H,return_eigenvectors = False)

相关问题 更多 >