将Python稀疏矩阵导入MATLAB

8 投票
2 回答
3742 浏览
提问于 2025-04-20 11:48

我在Python中有一个稀疏矩阵,使用的是CSR稀疏格式,现在我想把它导入到MATLAB里。可是MATLAB没有CSR这种稀疏格式,它只有一种稀疏格式可以用来处理所有类型的矩阵。因为这个矩阵在密集格式下非常大,所以我在想,怎么才能把它作为MATLAB的稀疏矩阵导入呢?

2 个回答

4

Matlab和Scipy的稀疏矩阵格式是可以互相兼容的。你需要在Scipy中获取矩阵的数据、索引和矩阵的大小,然后用这些信息在Matlab中创建一个稀疏矩阵。下面是一个例子:

from scipy.sparse import csr_matrix
from scipy import array

# create a sparse matrix
row = array([0,0,1,2,2,2])
col = array([0,2,2,0,1,2])
data = array([1,2,3,4,5,6])

mat = csr_matrix( (data,(row,col)), shape=(3,4) )

# get the data, shape and indices
(m,n) = mat.shape
s = mat.data
i = mat.tocoo().row
j = mat.indices

# display the matrix
print mat

这段代码会输出:

  (0, 0)        1
  (0, 2)        2
  (1, 2)        3
  (2, 0)        4
  (2, 1)        5
  (2, 2)        6

你可以用Python中的m、n、s、i和j这些值,在Matlab中创建一个矩阵:

m = 3;
n = 4;
s = [1, 2, 3, 4, 5, 6];
% Index from 1 in Matlab.
i = [0, 0, 1, 2, 2, 2] + 1;
j = [0, 2, 2, 0, 1, 2] + 1;

S = sparse(i, j, s, m, n, m*n)

这样就能得到相同的矩阵,只不过在Matlab中索引是从1开始的。

   (1,1)        1
   (3,1)        4
   (3,2)        5
   (1,3)        2
   (2,3)        3
   (3,3)        6
6

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

撰写回答