Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 289
user3821329 Avatar asked Sep 08 '14 14:09

user3821329


People also ask

How do you sparse a matrix in Matlab?

S = sparse( A ) converts a full matrix into sparse form by squeezing out any zero elements. If a matrix contains many zeros, converting the matrix to sparse storage saves memory. S = sparse( m,n ) generates an m -by- n all zero sparse matrix.

How do you read a sparse matrix in python?

One way to visualize sparse matrix is to use 2d plot. Python's matplotlib has a special function called Spy for visualizing sparse matrix. Spy is very similar to matplotlib's imshow, which is great for plotting a matrix or an array as an image. imshow works with dense matrix, while Spy works with sparse matrix.

How do you add a sparse matrix in python?

A simple and efficient way to add sparse matrices is to convert them to sparse triplet form, concatenate the triplets, and then convert back to sparse column format.


1 Answers

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
like image 107
hpaulj Avatar answered Oct 17 '22 01:10

hpaulj