Skip to main content
 首页 » 编程设计

python之将 MATLAB 中的 spdiags() 转换为 Python

2025年05月04日40daizhj

我正在尝试将 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 

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 有六种。