Skip to content Skip to sidebar Skip to footer

Opening A Mat File Using H5py And Convert Data Into A Numpy Matrix

I have a mat file which contains 2 different cells containing matrices of different size. I need to convert that data into a numpy array using h5py for an experiment (I'm new in h5

Solution 1:

Looking for matlab and h5py I find

read matlab v7.3 file into python list of numpy arrays via h5py (2014)

Reading a Matlab's cell array saved as a v7.3 .mat file with H5py (2015)

How to read a v7.3 mat file via h5py? (2013)

MATLAB structures and cells don't map directly onto h5 or numpy classes. So there's a tendency to embed them in object arrays. This issue arises when reading old .mat files with scipy.io.loadmat as well. To pull an element out of an dtype=object array you have use further indexing, which for 0d arrays can be a little tricky.

Let me illustrate

In [603]: a = np.arange(4)

Make a 1d array with 1 item, and insert a

In [604]: b = np.array([None], dtype=object)
In [605]: b[0] = a

In [606]: b
Out[606]: array([array([0, 1, 2, 3])], dtype=object)

retrieve a with indexing or item:

In[607]: b[0]Out[607]: array([0, 1, 2, 3])

In[608]: b.item()
Out[608]: array([0, 1, 2, 3])

but if it's a 0d numpy array:

In [618]: c=np.array(None)    
In [619]: c
Out[619]: array(None, dtype=object)
In [620]: c[()]=a

In [621]: c
Out[621]: array(array([0, 1, 2, 3]), dtype=object)

In [622]: c.item()
Out[622]: array([0, 1, 2, 3])

In [623]: c[()]
Out[623]: array([0, 1, 2, 3])

In this case you have to index with an empty tuple, ().

Solution 2:

You have to call the element as follow:

np.array(x)[0, 1]

Post a Comment for "Opening A Mat File Using H5py And Convert Data Into A Numpy Matrix"