4
votes

I have imported a Matlab *.mat file using scipy.io and trying to extract the 2D data from it. There are several arrays inside, and when I am trying to get them I got stuck at the last operation.

The data looks like the image below. When I try to index it: IndexError: too many indices for array

I have googled to the point that it looks like a single valued tuple, where the only element is my array. This in principle must be indexable, but it doesn't work. The type(data) returns <class 'numpy.ndarray'>

So the question is: how do I get my 2D array out of this data structure?

    data[0] # Doesn't work.

array in question

2
array[0]? Without telling us what you have tried, it's hard to say where your problem might lie. - Zinki
Could you add an example to generate a similar matrix or at least how you are trying to retrieve the data? What does it outputs if you execute my_array.shape? - Luca Cappelletti
If I knew how to generate a similar matrix, I would've known the answer. I have found a way around though, some voodoo coding, I will post the reply asap. - denis

2 Answers

5
votes

A search on loadmat should yield many SO questions that will help you pick apart this result. loadmat has to translate MATLAB objects into Python/numpy approximations.

data = io.loadmat(filename)

should produce a dictionary with some cover keys and various data keys. list(data.keys()) to identify those.

x = data['x']

should match the x variable in the MATLAB workspace. It could be a 2d, order F array, corresponding to a MATLAB matrix.

It could be (n,m) object dtype array, corresponding to a MATLAB cell.

It could be a structured array, where the field names correspond to a MATLAB struct attributes.

In your case it looks like you have a 0d object dtype array. The shape is (), an empty tuple (1d has (n,) shape, 2d has (n,m) shape, etc). You can pull the element out of a () array with:

 y[()]
 y.item()

The [()] looks odd, but it's logical. For a 1d array y[1] can be written as y[(1,)]. For 2d, y[1,2] and y[(1,2)] are the same. The indexing tuple should match the number of dimensions. Hence a () can index a () shape array.

0
votes

After some voodoo coding I have found a funny way to solve this:

The initial data is the zero-dimensional where the only element is the 2D array. The way to get this element out apparently is:

    z = data.item()[()][0]
    print(z)         

The final result is below I got my 2D array:

Workable 2D data