在Matlab/Octave中,spdiags([-8037.500 50.000 -12.500], 0:2, 1, 51)
给出以下输出:
(1, 1) -> -8037.5
(1, 2) -> 50
(1, 3) -> -12.500
但是,当我在Python中使用以下命令时,它不会产生类似于Matlab/Octave的结果:
^{pr2}$Python的spdiags()生成以下输出,其中缺少第1和第2个索引中的50
和-12.5
项:
array([[-8037.5, 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , 0. ]])
我看了一个类似问题的this答案,但我不确定我错在哪里。在
编辑:
我试图构建一个矩阵A
,它由A_diag1
,A_diag2
,和{A_diag1
和{
import numpy as np
import scipy as sp
A_diag1 = np.tile(np.array([-8037.500, 50, -12.5]), (3,1))
A_diag2 = np.reshape(np.repeat([1250, -18505, 1250], 49), (3, 49))
A_diag3 = np.tile(np.array([12.5, -50, 8037.500]), (3,1))
A = np.concatenate((sp.sparse.spdiags(A_diag1, np.r_[0:2 + 1], 1, 51).toarray(), \
sp.sparse.spdiags(A_diag2, np.r_[0:2 + 1], 49, 51).toarray(), \
sp.sparse.spdiags(A_diag3, np.r_[48:50 + 1], 1, 51).toarray()), axis=0)
但是,A
最后3行和列中的5个高亮显示的单元格显示为0/单数,如下面的快照所示。我希望那些高亮显示的单元格(当前显示为零)为非零。[您只需复制并粘贴上面的代码片段来复制A
矩阵,下面显示的快照就是从这个矩阵中获取的。]
编辑2:
下面使用sp.sparse.diags()
的代码按预期工作。与sp.sparse.spdiags
不同,使用sp.sparse.diags()
时结果形状(数组维度)的输入参数必须在列表中。在
import numpy as np
import scipy as sp
A_diag1 = np.array([[-8037.500], [50], [-12.5]])
A_diag2 = np.reshape(np.repeat([1250, -18505, 1250], 49), (3, 49))
A_diag3 = np.array([[12.5], [-50], [8037.500]])
A = np.concatenate((sp.sparse.diags(A_diag1, np.arange(0, 2 + 1), [1, 51]).toarray(), \
sp.sparse.diags(A_diag2, np.arange(0, 2 + 1), [49, 51]).toarray(), \
sp.sparse.diags(A_diag3, np.arange(48, 50 + 1), [1, 51]).toarray()), axis=0)
这就形成了一个稀疏矩阵(51,1),每一行都有一个值:
请注意,
spdiags
定义:Sparse
^{pr2}$diagonal format
将其数据存储在一个矩阵中,其中一部分可以“屏幕外”。所以使用起来有点棘手。我通常使用coo
样式的输入创建矩阵。在你想要的是它的转置(也许)
因此我们可以用以下方法重新创建
Mt
:如果我保存倍频程矩阵并加载它,我得到:
如果我把它转换成
dia
格式,就会得到类似Mt
的格式:{cd7>可能更直观一些:
(})
r_
表达式也可以是np.arange(0,3)
和{它们可以与
sparse.vstack
(它结合了coo
格式属性)与快照匹配。(我还需要弄清楚你想创造什么)。在
sparse.spdiags(data, diags, m, n)
只是调用sparse.dia_matrix((data, diags), shape=(m,n))
的另一种方式回到
sparse.diags
,如果您想要3条对角线,每个对角线都填充一个来自data
的值,我们可以使用:所以
sp1
必须看起来像我无法解释您的观察结果(虽然不是一个matlab用户;但我可以确认octave是像您所说的那样做的),但是按照scipy的example-usage,您可以使用以下方法实现这个结果:
输出:
^{pr2}$平铺步骤生成:
当然,一切都是基于0索引的。在
相关问题 更多 >
编程相关推荐