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

后端 未结 3 1164
不思量自难忘°
不思量自难忘° 2020-12-31 21:12

I saved a cell array as a .mat file in Matlab as follows:

test = {\'hello\'; \'world!\'};
save(\'data.mat\', \'test\', \'-v7.3\')

How can I

3条回答
  •  被撕碎了的回忆
    2020-12-31 21:48

    Writing in Matlab:

    test = {'Hello', 'world!'; 'Good', 'morning'; 'See', 'you!'};
    save('data.mat', 'test', '-v7.3') % v7.3 so that it is readable by h5py
    

    enter image description here

    Reading in Python (works for any number or rows or columns, but assumes that each cell is a string):

    import h5py
    import numpy as np
    
    data = []
    with h5py.File("data.mat") as f:
        for column in f['test']:
            row_data = []
            for row_number in range(len(column)):            
                row_data.append(''.join(map(unichr, f[column[row_number]][:])))   
            data.append(row_data)
    
    print data
    print np.transpose(data)
    

    Output:

    [[u'Hello', u'Good', u'See'], [u'world!', u'morning', u'you!']]
    
    [[u'Hello' u'world!']
     [u'Good' u'morning']
     [u'See' u'you!']]
    

提交回复
热议问题