[英]Converting a scipy.sparse matrix into an equivalent MATLAB sparse matrix
我有一个scipy.sparse.lil_matrix
,我想使用适用于Python的MATLAB引擎API馈入MATLAB方法(不是我编写的)。 到目前为止,我所看到的帖子要么是关于如何将MATLAB稀疏矩阵转换为等效的python,要么是需要修改我宁愿规避的matlab代码。
在内部,我相信MATLAB使用csc
like格式。 但是构造(至少在我几年前使用过)具有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
。
在八度会话中:
>> 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兼容方式处理稀疏矩阵。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.