Search code examples
pythonnumpyscipysparse-matrix

Matlab to Python sparse matrix conversion , overcoming the zero index problem


I have an N x N sparse matrix in Matlab, that has cell values indexed by (r,c) pairs such that r and c are unique id's.

The problem is, that after converting this matrix into Python, all of the indices values are decremented by 1.

For example:

Before                     After
(210058,10326) = 1         (210057,10325) = 1

Currently, I am doing the following to counter this:

mat_contents = sparse.loadmat(filename)
G = mat_contents['G']
I,J = G.nonzero()
I += 1
J += 1
V = G.data
G = sparse.csr_matrix((V,(I,J)))

I have also tried using different options in scipy.sparse.io.loadmat {matlab_compatible, mat_dtype}, but neither worked.

I am looking for a solution that will give me the same indices as the Matlab matrix. Solutions that do not require reconstructing the matrix would be ideal, but I am also curious how others have gotten around this problem.


Solution

  • Thank you all for the good advice.

    I decided to stick with Python. I do most of my data transfers between Matlab and Python using text files now.