Scipy: The sparse matrix that "scipy.io.savemat" function save cannot be properly loaded in Matlab R2014a

Created on 9 Jul 2015  路  2Comments  路  Source: scipy/scipy

My matlab version: R2014a (8.3.0.532) 64-bit (glnxa64)
My scipy version: 0.15.1 (in python3)
My operating system: CentOS release 6.6 (Final)

My python3 code to save a csr_matrix:

import numpy as np
from scipy.io import savemat
from scipy.sparse import csr_matrix

a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
b = csr_matrix(a)
savemat('test.mat', {'b': b})

Later I load test.mat in my matlab:

load test.mat
b

The result is:

b =

  9.9e-323 *

   (1,1)       0.0500
   (2,1)       0.2500
   (1,2)       0.1000
   (2,2)       0.3000
   (1,3)       0.1500
   (2,3)       0.3500
   (1,4)       0.2000
   (2,4)       0.4000

The result is very strange, and the reason seems to be the default .mat file format changed to v7.3 in newer version of matlab. I just think maybe it's better to show warning message in scipy when user use savemat function. Thank you.

defect scipy.io

Most helpful comment

After testing the code below:

import numpy as np
from scipy.io import savemat
from scipy.sparse import csr_matrix

a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype='double')
b = csr_matrix(a)
savemat('test.mat', {'b': b})

only convert a into a float type, the matlab works well:

>> load test.mat
>> b

b =

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

It seems that object MatFile5Writer in function savemat could not correctly handle integer type, cause a format bug in matlab
function savemat: https://github.com/scipy/scipy/blob/v0.15.1/scipy/io/matlab/mio.py#L203

All 2 comments

After testing the code below:

import numpy as np
from scipy.io import savemat
from scipy.sparse import csr_matrix

a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype='double')
b = csr_matrix(a)
savemat('test.mat', {'b': b})

only convert a into a float type, the matlab works well:

>> load test.mat
>> b

b =

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

It seems that object MatFile5Writer in function savemat could not correctly handle integer type, cause a format bug in matlab
function savemat: https://github.com/scipy/scipy/blob/v0.15.1/scipy/io/matlab/mio.py#L203

Was this page helpful?
0 / 5 - 0 ratings