Import sparse python matrix in MATLAB

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

+5
source share
2 answers

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

 In [1]: from scipy.io import savemat 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 tracks the difference at the starting point of the index.

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 
+2
source

Matlab and Scipy sparse matrix formats are compatible. You need to get the data, indices and matrix matrix size in Scipy and use them to create a sparse matrix in Matlab. Here is an example:

 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 

What prints:

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

Use the values ​​m, n, s, i and j from Python to create a matrix in 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) 

Which gives the same matrix, only indexed from 1.

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

Source: https://habr.com/ru/post/1202081/


All Articles