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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With