我在 python 中有一个 CSR 稀疏格式的稀疏矩阵,我想将它导入 MATLAB。 MATLAB 没有 CSR 稀疏格式。对于所有类型的矩阵,它只有 1 种稀疏格式。由于密集格式的矩阵非常大,我想知道如何将其导入为 MATLAB 稀疏矩阵?
最佳答案
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]])
请注意,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
关于python - 将 python 稀疏矩阵导入 MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25727051/