MATLAB 中的 spdiags() 变成 Python

spdiags() in MATLAB into Python

我正在尝试将 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 函数的作用是什么,是否有相同 return 的 Python 实现可用?

好吧,这个答案只能说到表面,但是:

矩阵有不同的存储格式。当然,有最直观的 "row after row" 和 "column after column" 格式,但也有只有少数非零项的矩阵格式,这当然会节省大量内存(并且可能会节省很多CPU) 如果使用正确。

所以,这些对角稀疏矩阵就是matlab中专门存储的矩阵的这种情况;如果您不关心计算优势,只需使用 diag,它在功能上 100% 等效(但不会生成稀疏矩阵)。

稀疏矩阵存储的存在是 Matlab 的一项功能,scipy 实际上(我对此感到惊讶)也具有该功能。因此,如果符合您的需要,请使用 scipy 方法!

在 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

存储在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

等价的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>

这里使用dia格式,但是很容易用x.tocsc().

转换成csc(相当于Octave格式)

要查看相同的坐标和值,我们可以使用 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}

相同的值,针对基于 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]])

Octave/MATLAB 按列排列值,numpy 按行排列值,因此 reshape 不同。 numpy 矩阵是 MATLAB 等效矩阵的转置。

请注意,两者都省略了 9(4 个项目映射到 3 元素对角线上)。

另一个参数是要设置的对角线列表,[-1,0,1] 和最终形状 (5,4)

参数上的大部分差异都得做MATLAB和numpy的基本差异。另一个区别是 MATLAB 只有一个稀疏矩阵表示,scipy 有六个。

我有一个解决方案,它真的很容易尝试这个,你会从 MATLAB 和 python 得到相同的答案,python 你有时必须更改输入的格式。

所以试试这个:

sparse.spdiags(your_Array.T, diags, m, n)