在python中访问时如何保留matlab结构?

问题描述 投票:10回答:3

我有一个我使用的mat文件

from scipy import io
mat = io.loadmat('example.mat')

从matlab开始,example.mat包含以下结构

    >> load example.mat
    >> data1

    data1 =

            LAT: [53x1 double]
            LON: [53x1 double]
            TIME: [53x1 double]
            units: {3x1 cell}


    >> data2

    data2 = 

            LAT: [100x1 double]
            LON: [100x1 double]
            TIME: [100x1 double]
            units: {3x1 cell}

在matlab中,我可以像data2.LON一样轻松访问数据。它在python中并不是那么简单。虽然喜欢它,但它给了我几个选项

mat.clear       mat.get         mat.iteritems   mat.keys        mat.setdefault  mat.viewitems   
mat.copy        mat.has_key     mat.iterkeys    mat.pop         mat.update      mat.viewkeys    
mat.fromkeys    mat.items       mat.itervalues  mat.popitem     mat.values      mat.viewvalues    

有可能在python中保留相同的结构吗?如果没有,如何最好地访问数据?我正在使用的当前python代码非常难以使用。

谢谢

python matlab structure mat-file preserve
3个回答
10
投票

找到关于matlab struct和python的本教程

http://docs.scipy.org/doc/scipy/reference/tutorial/io.html


1
投票

当我需要从MATLAB中将数据加载到Python中时,它存储在结构数组{strut_1,struct_2}中。我从使用scipy.io.loadmat加载的对象中提取键和值列表。然后我可以将它们组装到自己的变量中,或者如果需要,将它们重新打包成字典。在所有情况下使用exec命令可能并不合适,但如果您只是尝试处理数据,则它可以正常工作。

# Load the data into Python     
D= sio.loadmat('data.mat')

# build a list of keys and values for each entry in the structure
vals = D['results'][0,0] #<-- set the array you want to access. 
keys = D['results'][0,0].dtype.descr

# Assemble the keys and values into variables with the same name as that used in MATLAB
for i in range(len(keys)):
    key = keys[i][0]
    val = np.squeeze(vals[key][0][0])  # squeeze is used to covert matlat (1,n) arrays into numpy (1,) arrays. 
    exec(key + '=val')

0
投票

(!)如果在*.mat文件中保存了嵌套结构,则需要检查字典中io.loadmat输出的项是否为Matlab结构。例如,如果在Matlab中

>> thisStruct

ans =
      var1: [1x1 struct]
      var2: 3.5

>> thisStruct.var1

ans =
      subvar1: [1x100 double]
      subvar2: [32x233 double]

然后在scipy.io.loadmat nested structures (i.e. dictionaries)中通过合并使用代码

© www.soinside.com 2019 - 2024. All rights reserved.