使用H5py读取保存为v7.3 .mat文件的Matlab单元格数组 [英] Reading a Matlab's cell array saved as a v7.3 .mat file with H5py

查看:91
本文介绍了使用H5py读取保存为v7.3 .mat文件的Matlab单元格数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Matlab中将单元格数组另存为.mat文件,如下所示:

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

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

如何使用H5py将其导入为Python中的字符串列表?

How can I import it as the list of strings in Python with H5py?

我尝试了

f = h5py.File('data.mat', 'r')
print f.get('test')
print f.get('test')[0]

打印输出:

<HDF5 dataset "test": shape (1, 2), type "|O8">
[<HDF5 object reference> <HDF5 object reference>]

如何取消引用它以获取Python中的字符串['hello', 'world!']列表?

How can I dereference it to get the list of strings ['hello', 'world!'] in Python?

推荐答案

在Matlab中编写:

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

使用Python进行阅读(适用于任何数字,行或列,但假定每个单元格都是一个字符串):

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)

输出:

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

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

这篇关于使用H5py读取保存为v7.3 .mat文件的Matlab单元格数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆