-2

Instead of loading a MATLAB struct as a dict (as described in http://docs.scipy.org/doc/scipy/reference/tutorial/io.html and other related questions), scipy.io.loadmat is loading it as a strange ndarray, where the values are an array of arrays, and the field names are taken to be the dtype. Minimal example:

(MATLAB):

>> a = struct('b',0)

a = 

    b: 0

>> save('simple_struct.mat','a')

(Python):

In[1]:
import scipy.io as sio
matfile = sio.loadmat('simple_struct.mat')
a = matfile['a']
a

Out[1]:
array([[([[0]],)]], 
      dtype=[('b', 'O')])

This problem persists in Python 2 and 3.

  • 2
    Did you actually read the [MATLAB structs section](http://docs.scipy.org/doc/scipy/reference/tutorial/io.html#matlab-structs) in the documentation link you used above? It looks like this is all expected behavior.... It goes on to describe how you can use the `squeeze_me` and `struct_as_record` parameters. – rkersh Aug 19 '16 at 18:08
  • Not closely enough! Thanks. I guess between this question [link](http://stackoverflow.com/questions/1984714/how-to-access-fields-in-a-struct-imported-from-a-mat-file-using-loadmat-in-pyth) and now, structs_as_record has become True by default. – Dan Mossing Aug 19 '16 at 18:27

1 Answers1

0

This is expected behavior. Numpy is just showing you have MATLAB is storing your data under-the-hood.

MATLAB structs are 2+D cell arrays where one dimension is mapped to a sequence of strings. In Numpy, this same data structure is called a "record array", and the dtype is used to store the name. And since MATLAB matrices must be at least 2D, the 0 you stored in MATLAB is really a 2D matrix with dimensions (1, 1).

So what you are seeing in the scipy.io.loadmat is how MATLAB is storing your data (minus the dtype bit, MATLAB doesn't have such a thing). Specifically, it is a 2D [1, 1] array (that is what Numpy calls cell arrays), where one dimension is mapped to a string, containing a [1, 1] 2D array. MATLAB hides some of these details from you, but numpy doesn't.

TheBlackCat
  • 9,791
  • 3
  • 24
  • 31