将python稀疏矩阵导入MATLAB

use*_*329 7 python matlab numpy scipy sparse-matrix

我在python中使用CSR稀疏格式的稀疏矩阵,我想将其导入MATLAB.MATLAB没有CSR稀疏格式.它对所有类型的矩阵只有1种稀疏格式.由于矩阵在密集格式中非常大,我想知道如何将其作为MATLAB稀疏矩阵导入?

hpa*_*ulj 5

scipy.io.savemat保存在一个MATLAB兼容格式稀疏矩阵:

In [1]: from scipy.io import savemat, loadmat
In [2]: from scipy import sparse
In [3]: M = sparse.csr_matrix(np.arange(12).reshape(3,4))
In [4]: savemat('temp', {'M':M})

In [8]: x=loadmat('temp.mat')
In [9]: x
Out[9]: 
{'M': <3x4 sparse matrix of type '<type 'numpy.int32'>'
    with 11 stored elements in Compressed Sparse Column format>,
 '__globals__': [],
 '__header__': 'MATLAB 5.0 MAT-file Platform: posix, Created on: Mon Sep  8 09:34:54 2014',
 '__version__': '1.0'}

In [10]: x['M'].A
Out[10]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
Run Code Online (Sandbox Code Playgroud)

请注意,savemat将其转换为csc. 它还透明地处理索引起点差异。

并在Octave

octave:4> load temp.mat
octave:5> M
M =
Compressed Column Sparse (rows = 3, cols = 4, nnz = 11 [92%])
  (2, 1) ->  4
  (3, 1) ->  8
  (1, 2) ->  1
  (2, 2) ->  5
  ...

octave:8> full(M)
ans =    
    0    1    2    3
    4    5    6    7
    8    9   10   11
Run Code Online (Sandbox Code Playgroud)