12

我有一个我使用的 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 代码很难使用。

谢谢

4

4 回答 4

13

找到了这个关于 matlab struct 和 python 的教程

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

于 2012-08-14T15:22:23.417 回答
5

当我需要从 MATLAB 将存储在结构数组 {strut_1,struct_2} 中的数据加载到 Python 中时,我会从我加载的对象中提取键和值列表 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')
于 2018-03-04T17:47:52.940 回答
2

这会将 mat 结构作为字典返回

def _check_keys( dict):
"""
checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries
"""
for key in dict:
    if isinstance(dict[key], sio.matlab.mio5_params.mat_struct):
        dict[key] = _todict(dict[key])
return dict


def _todict(matobj):
    """
    A recursive function which constructs from matobjects nested dictionaries
    """
    dict = {}
    for strg in matobj._fieldnames:
        elem = matobj.__dict__[strg]
        if isinstance(elem, sio.matlab.mio5_params.mat_struct):
            dict[strg] = _todict(elem)
        else:
            dict[strg] = elem
    return dict


def loadmat(filename):
    """
    this function should be called instead of direct scipy.io .loadmat
    as it cures the problem of not properly recovering python dictionaries
    from mat files. It calls the function check keys to cure all entries
    which are still mat-objects
    """
    data = sio.loadmat(filename, struct_as_record=False, squeeze_me=True)
    return _check_keys(data)
于 2020-12-08T08:36:28.277 回答
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 嵌套结构(即字典)中通过合并使用代码

于 2015-04-29T20:24:07.820 回答