reading v 7.3 mat file in python

后端 未结 8 1741
情书的邮戳
情书的邮戳 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:45

    This function reads Matlab-produced HDF5 .mat files, and returns a structure of nested dicts of Numpy arrays. Matlab writes matrices in Fortran order, so this also transposes matrices and higher-dimensional arrays into conventional Numpy order arr[..., page, row, col].

    import h5py
    
    def read_matlab(filename):
        def conv(path=''):
            p = path or '/'
            paths[p] = ret = {}
            for k, v in f[p].items():
                if type(v).__name__ == 'Group':
                    ret[k] = conv(f'{path}/{k}')  # Nested struct
                    continue
                v = v[()]  # It's a Numpy array now
                if v.dtype == 'object':
                    # HDF5ObjectReferences are converted into a list of actual pointers
                    ret[k] = [r and paths.get(f[r].name, f[r].name) for r in v.flat]
                else:
                    # Matrices and other numeric arrays
                    ret[k] = v if v.ndim < 2 else v.swapaxes(-1, -2)
            return ret
    
        paths = {}
        with h5py.File(filename, 'r') as f:
            return conv()
    
    0 讨论(0)
  • 2020-12-02 09:54
    import h5py
    import numpy as np
    filepath = '/path/to/data.mat'
    arrays = {}
    f = h5py.File(filepath)
    for k, v in f.items():
        arrays[k] = np.array(v)
    

    you should end up with your data in the arrays dict, unless you have MATLAB structures, I suspect. Hope it helps!

    0 讨论(0)
提交回复
热议问题