在内部,我相信 MATLAB 使用 csc 之类的格式。但是构造是(至少在我几年前使用它时)使用coo 样式输入 - 数据、行、列。
我建议在 MATLAB 中创建一个稀疏矩阵,并将其(在 HDF5 之前的模式下)保存到 .mat 中。然后用scipy.io.loadmat 加载它。然后在将scipy.sparse 矩阵写回.mat 时使用该结果作为指导。
scipy.sparse 有一个save 函数,但它使用np.savez 来编写各自的属性数组。如果您有可以处理 .npy 文件的 MATLAB 代码,您可能可以加载这样的保存文件(再次使用 coo 格式)。
===
一个测试。
创建并保存一个稀疏矩阵:
In [263]: from scipy import io, sparse
In [264]: M = sparse.random(10,10,.2,'coo')
In [265]: io.savemat('sparse.mat', {'M':M})
Python 端的测试负载:
In [268]: io.loadmat('sparse.mat')
Out[268]:
{'__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Wed Jul 3 11:41:23 2019',
'__version__': '1.0',
'__globals__': [],
'M': <10x10 sparse matrix of type '<class 'numpy.float64'>'
with 20 stored elements in Compressed Sparse Column format>}
所以 savemat 在保存之前将coo 格式转换为csc。
在 Octave 会话中:
>> load sparse.mat
>> M
M =
Compressed Column Sparse (rows = 10, cols = 10, nnz = 20 [20%])
(4, 1) -> 0.41855
(6, 1) -> 0.33456
(7, 1) -> 0.47791
(4, 3) -> 0.27464
(2, 4) -> 0.96700
(3, 4) -> 0.60283
(10, 4) -> 0.41400
(1, 5) -> 0.57004
(2, 5) -> 0.44211
(1, 6) -> 0.63884
(3, 7) -> 0.012127
(8, 7) -> 0.77328
(8, 8) -> 0.25287
(10, 8) -> 0.46280
(1, 9) -> 0.0022617
(6, 9) -> 0.70874
(1, 10) -> 0.79101
(3, 10) -> 0.81999
(6, 10) -> 0.12515
(9, 10) -> 0.60660
所以看起来savemat/loadmat 代码以与 MATLAB 兼容的方式处理稀疏矩阵。