reading v 7.3 mat file in python

后端 未结 8 1766
情书的邮戳
情书的邮戳 2020-12-02 09:16

I am trying to read a matlab file with the following code

import scipy.io
mat = scipy.io.loadmat(\'test.mat\')

and it gives me the followin

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 09:42

    Despite hours of searching I've not found how to access Matlab v7.3 structures either. Hopefully this partial answer will help someone, and I'd be very happy to see extra pointers.

    So starting with (I think the [0][0] arises from Matlab giving everything to dimensions):

    f = h5py.File('filename', 'r')
    f['varname'][0][0]
    

    gives: < HDF5 object reference >

    Pass this reference to f again:

    f[f['varname'][0][0]]
    

    which gives an array: convert this to a numpy array and extract the value (or, recursively, another < HDF5 object reference > :

    np.array(f[f['varname'][0][0]])[0][0]
    

    If accessing the disk is slow, maybe loading to memory would help.


    Further edit: after much futile searching my final workaround (I really hope someone else has a better solution!) was calling Matlab from python which is pretty easy and fast:

    eng = matlab.engine.start_matlab()  # first fire up a Matlab instance
    eng.quit()
    eng = matlab.engine.connect_matlab()  # or connect to an existing one
    eng.sqrt(4.0)
    x = 4.0
    eng.workspace['y'] = x
    a = eng.eval('sqrt(y)')
    print(a)
    x = eng.eval('parameterised_function_in_Matlab(1, 1)', nargout=1)
    a = eng.eval('Structured_variable{1}{2}.object_name')  # (nested cell, cell, object)
    

提交回复
热议问题