Search code examples
pythonmatlabnumpyscipysparse-matrix

importing a python sparse matrix into MATLAB


I've a Sparse matrix in CSR Sparse format in python and I want to import it to MATLAB. MATLAB does not have a CSR Sparse format. It has only 1 Sparse format for all kind of matrices. Since the matrix is very large in the dense format I was wondering how could I import it as a MATLAB sparse matrix?


Solution

  • The scipy.io.savemat saves sparse matrices in a MATLAB compatible format:

    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]])
    

    Note that savemat converted it to csc. It also transparently takes care of the index starting point difference.

    And in 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