微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将matlab数据结构读入numpy数组

如何解决将matlab数据结构读入numpy数组

我有一组 MAT 文件,其中包含一个 ma​​tlab struct。该结构有一堆数组。我想打开文件并将它们全部传输到数组中。到目前为止,我已经编写了以下代码

import h5py
>>> fs = h5py.File('statistics_VAD.mat','r')
>>> list(fs.keys())
['#refs#','data']
>>> 
>>> fs['data'].visititems(lambda n,o:print(n,o))
C <HDF5 dataset "C": shape (100,1),type "|O">
P <HDF5 dataset "P": shape (100,type "|O">
V <HDF5 dataset "V": shape (100,type "|O">
Wn <HDF5 dataset "Wn": shape (100,type "|O">
X <HDF5 dataset "X": shape (100,type "|O">
a <HDF5 dataset "a": shape (100,type "|O">
dn <HDF5 dataset "dn": shape (100,type "|O">
>>> struArray = fs['data']
>>> print(struArray['P'])
<HDF5 dataset "P": shape (100,type "|O">

我不知道如何将 HDF5 dataset "P" 转移到 numpy 数组。任何建议将不胜感激

解决方法

下面的代码是我的评论(dtd 2021-03-01)中提到的示例。它从 NumPy 数组创建 2 个数据集,然后是一个具有 2 个对象引用的数据集,每个数据集 1 个。然后展示了如何使用对象引用来访问数据。为完整性起见,还完成了带有区域参考的第二个数据集。

注意 h5f[] 是如何使用两次的:内部一个获取对象,外部一个从对象引用中获取数据。这是一种微妙的方式,让不熟悉引用的用户感到困惑。

import numpy as np
import h5py

with h5py.File('SO_66410592.h5','w') as h5f :
    # Create 2 datasets using numpy arrays
    arr = np.arange(100).reshape(20,5)
    h5f.create_dataset('array1',data=arr)    
    arr = np.arange(100,-1).reshape(20,5)
    h5f.create_dataset('array2',data=arr) 
    
    # Create a dataset of OBJECT references: 
    h5f.create_dataset('O_refs',(10,),dtype=h5py.ref_dtype)
    h5f['O_refs'][0] = h5f['array1'].ref
    print (h5f['O_refs'][0])
    print (h5f[ h5f['O_refs'][0] ])
    print (h5f[ h5f['O_refs'][0] ][0,:])
    h5f['O_refs'][1] = h5f['array2'].ref
    print (h5f['O_refs'][1])
    print (h5f[ h5f['O_refs'][1] ])
    print (h5f[ h5f['O_refs'][1] ][-1,:])

    # Create a dataset of REGION references: 
    h5f.create_dataset('R_refs',dtype=h5py.regionref_dtype)
    h5f['R_refs'][0] = h5f['array1'].regionref[0,:]
    print (h5f['R_refs'][0])
    print (h5f[ h5f['R_refs'][0] ])    
    print (h5f[ h5f['R_refs'][0] ] [ h5f['R_refs'][0] ]) 
    h5f['R_refs'][1] = h5f['array2'].regionref[-1,:]
    print (h5f['R_refs'][1])
    print (h5f[ h5f['R_refs'][1] ])    
    print (h5f[ h5f['R_refs'][1] ] [ h5f['R_refs'][1] ]) 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。