【问题标题】:importing a python sparse matrix into MATLAB将 python 稀疏矩阵导入 MATLAB
【发布时间】:2014-11-01 20:06:08
【问题描述】:

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

【问题讨论】:

    标签: python matlab numpy scipy sparse-matrix


    【解决方案1】:

    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
    

    【讨论】:

    • 谢谢。这是直接的方法。
    【解决方案2】:

    MatlabScipy 稀疏矩阵格式是兼容的。您需要在 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)
    

    给出相同的矩阵,仅从 1 开始索引。

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

    【讨论】:

    • 谢谢。只是一个小的建议修改。对于 sparse 命令的最后一个(第六个)参数,我们可以使用 nnz 方法的结果而不是 m*n 来节省空间(或者干脆省略它并传递 5 个具有相同效果的参数)。
    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 2017-07-02
    • 2015-10-14
    • 2013-04-11
    • 1970-01-01
    • 2023-04-10
    • 2012-06-20
    • 2014-02-08
    相关资源
    最近更新 更多