Python:scipy.sparse.diags 矩阵中的元素分配
Python: Element assignment in a scipy.sparse.diags matrix
我目前正在尝试更改我使用 scipy.sparse.diags
函数创建的矩阵中的一行。但是,returns 出现以下错误,提示我无法分配给该对象:
TypeError: 'dia_matrix' object does not support item assignment
有没有什么办法可以解决这个问题而不必更改用于形成三对角矩阵的原始向量?以下是我的代码:
def Mass_Matrix(x0):
"""Finds the Mass matrix for any non uniform mesh x0"""
x0 = np.array(x0)
N = len(x0) - 1
h = x0[1:] - x0[:-1]
a = np.zeros(N+1)
a[0] = h[0]/3
for j in range(1,N):
a[j] = h[j-1]/3 + h[j]/3
a[N] = h[N-1]/3
b = h/6
c = h/6
data = [a.tolist(), b.tolist(), c.tolist()]
Positions = [0,1,-1]
Mass_Matrix = diags(data, Positions, (N+1,N+1))
return Mass_Matrix
def Initial_U(x0): #BC here
x0 = np.array(x0)
h = x0[1:] - x0[:-1]
N = len(x0) - 1
Mass = Mass_Matrix(x0)
Mass[0] = 0 #ITEM ASSIGNMENT ERROR
print Mass.toarray()
对于使用您的函数定义的稀疏矩阵:
x0=np.arange(10)
mm=Mass_Matrix(x0)
csr
格式是通常用于计算的格式,例如矩阵乘法和 linalg 求解。它确实定义了赋值,但给出了效率警告:
In [29]: mmr=mm.tocsr()
In [30]: mmr[0]=0
/usr/lib/python3/dist-packages/scipy/sparse/compressed.py:690: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
SparseEfficiencyWarning)
lil
工作正常
In [31]: mml=mm.tolil()
In [32]: mml[0]=0
许多 sparse
函数和方法将一种格式转换为另一种格式以利用它们各自的优势。但是开发人员还没有实现所有可能的组合。您需要阅读各种格式的优缺点,并注意每种格式的方法。
我目前正在尝试更改我使用 scipy.sparse.diags
函数创建的矩阵中的一行。但是,returns 出现以下错误,提示我无法分配给该对象:
TypeError: 'dia_matrix' object does not support item assignment
有没有什么办法可以解决这个问题而不必更改用于形成三对角矩阵的原始向量?以下是我的代码:
def Mass_Matrix(x0):
"""Finds the Mass matrix for any non uniform mesh x0"""
x0 = np.array(x0)
N = len(x0) - 1
h = x0[1:] - x0[:-1]
a = np.zeros(N+1)
a[0] = h[0]/3
for j in range(1,N):
a[j] = h[j-1]/3 + h[j]/3
a[N] = h[N-1]/3
b = h/6
c = h/6
data = [a.tolist(), b.tolist(), c.tolist()]
Positions = [0,1,-1]
Mass_Matrix = diags(data, Positions, (N+1,N+1))
return Mass_Matrix
def Initial_U(x0): #BC here
x0 = np.array(x0)
h = x0[1:] - x0[:-1]
N = len(x0) - 1
Mass = Mass_Matrix(x0)
Mass[0] = 0 #ITEM ASSIGNMENT ERROR
print Mass.toarray()
对于使用您的函数定义的稀疏矩阵:
x0=np.arange(10)
mm=Mass_Matrix(x0)
csr
格式是通常用于计算的格式,例如矩阵乘法和 linalg 求解。它确实定义了赋值,但给出了效率警告:
In [29]: mmr=mm.tocsr()
In [30]: mmr[0]=0
/usr/lib/python3/dist-packages/scipy/sparse/compressed.py:690: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
SparseEfficiencyWarning)
lil
工作正常
In [31]: mml=mm.tolil()
In [32]: mml[0]=0
许多 sparse
函数和方法将一种格式转换为另一种格式以利用它们各自的优势。但是开发人员还没有实现所有可能的组合。您需要阅读各种格式的优缺点,并注意每种格式的方法。