如何使用Python中的loadmat访问从.mat文件导入的结构体中的字段?

8

跟随这个问题,它提出了如何使用Scipy读取在Matlab中创建的.mat文件并回答了该问题。我想知道如何访问导入结构体中的字段。

我有一个Matlab文件,可以从中导入结构体:

>> load bla % imports a struct called G
>> G

G = 

         Inp: [40x40x2016 uint8]
         Tgt: [8x2016 double]
         Ltr: [1x2016 double]
    Relevant: [1 2 3 4 5 6 7 8]

现在我希望在Python中做同样的事情:
x = scipy.io.loadmat('bla.mat')
>>> x
{'__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file, Platform: PCWIN, Created on: Wed Jun 07 21:17:24 2006', 'G': array([[<scipy.io.matlab.mio5.mat_struct object at 0x0191F230>]], dtype=object), '__globals__': []}
>>> x['G']
array([[<scipy.io.matlab.mio5.mat_struct object at 0x0191F230>]], dtype=object)
>>> G = x['G']
>>> G
array([[<scipy.io.matlab.mio5.mat_struct object at 0x0191F230>]], dtype=object)

问题是,我该如何访问结构体G的成员:InpTgtLtrRelevant,就像在Matlab中那样访问它们?

help(G)和dir(G)的输出是什么(G[0]同理)? - Kimvais
如果您使用 x = scipy.io.loadmat('bla.mat',struct_as_record=True) 会发生什么?请参见 http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html - unutbu
1个回答

6

首先,我建议尽可能升级到Scipy svn - 最近matlab io进行了积极的开发,有一些非常显著的速度提升。

此外,如上所述,值得尝试struct_as_record=True。但是,您应该能够通过交互式操作来取得输出。

您的G是一个mio结构对象的数组 - 您可以检查 G.shape 例如。在这种情况下,我认为G = x['G'][0,0] 应该给出您想要的对象。然后您应该能够访问G.Inp 等等。


1
这对我也起作用了,但是我必须将其作为下标/字典访问,即x['G'][0, 0]['Inp']。 - eacousineau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接