Gal*_*len 2 python matlab function scipy sparse-matrix
我正在尝试将 MATLAB 实现转换为 Python 3 实现。我发现了一个我不理解的函数 spdiags(),并且也不知道如何将它翻译成 Python 3。
有关该函数的 MATLAB 文档位于: http://www.mathworks.com/help/matlab/ref/spdiags.html
有关同名函数的 Scipy 文档位于: http://docs.scipy.org/doc/scipy/reference/ generated/scipy.sparse.spdiags.html
MATLAB 函数的作用是什么?是否有相同返回值的 Python 实现?
在 Octave(MATLAB 替代方案)中,其文档中的示例:
octave:7> x = spdiags (reshape (1:12, 4, 3), [-1 0 1], 5, 4);
octave:8> full(x) # display as a full or dense matrix
ans =
5 10 0 0
1 6 11 0
0 2 7 12
0 0 3 8
0 0 0 4
Run Code Online (Sandbox Code Playgroud)
存储的实际值x是:
x =
Compressed Column Sparse (rows = 5, cols = 4, nnz = 11 [55%])
(1, 1) -> 5
(2, 1) -> 1
(1, 2) -> 10
(2, 2) -> 6
(3, 2) -> 2
(2, 3) -> 11
(3, 3) -> 7
(4, 3) -> 3
(3, 4) -> 12
(4, 4) -> 8
(5, 4) -> 4
Run Code Online (Sandbox Code Playgroud)
等价表达式scipy.sparse:
In [294]: x = sparse.spdiags(np.arange(1,13).reshape(3,4), [-1, 0, 1], 5, 4)
In [295]: x.A # display as normal numpy array
Out[295]:
array([[ 5, 10, 0, 0],
[ 1, 6, 11, 0],
[ 0, 2, 7, 12],
[ 0, 0, 3, 8],
[ 0, 0, 0, 4]])
In [296]: x
Out[296]:
<5x4 sparse matrix of type '<class 'numpy.int32'>'
with 11 stored elements (3 diagonals) in DIAgonal format>
Run Code Online (Sandbox Code Playgroud)
它使用该dia格式,但很容易从 转换为csc(相当于 Octave 格式)x.tocsc()。
要查看相同的坐标和值,我们可以使用以下dok格式(字典子类):
In [299]: dict(x.todok())
Out[299]:
{(0, 1): 10,
(1, 2): 11,
(3, 2): 3,
(0, 0): 5,
(3, 3): 8,
(2, 1): 2,
(2, 3): 12,
(4, 3): 4,
(2, 2): 7,
(1, 0): 1,
(1, 1): 6}
Run Code Online (Sandbox Code Playgroud)
相同的值,针对基于 0 的索引进行调整。
在这两种情况下,对角线值都来自矩阵:
octave:10> reshape(1:12, 4, 3)
ans =
1 5 9
2 6 10
3 7 11
4 8 12
In [302]: np.arange(1,13).reshape(3,4)
Out[302]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
Run Code Online (Sandbox Code Playgroud)
Octave/MATLAB 按列、numpy按行排列值,因此reshape. 该numpy矩阵是 MATLAB 等效矩阵的转置。
请注意,9两者都省略了(4 个项目映射到 3 元素对角线上)。
另一个参数是要设置的对角线列表[-1,0,1]和最终形状(5,4)。
大多数参数差异都与 MATLAB 和 numpy 之间的基本差异有关。另一个区别是 MATLAB 只有一种稀疏矩阵表示,而 scipy 有六种。