使用Python存储Matlab文件

2024-04-24 21:03:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个复杂的数据结构

data = {}
temp = {}

data['bigdata'] = temp;

在此之后,我将“key”和“data”值从其他数据结构复制到temp中,如下所示

^{pr2}$

以及

for key in backup.keys():
    for val in backup[key]:
        temp[key].append(val);

之后如果我做了

sio.savemat(outputMATfile,data,oned_as ='column')

这是在给我错误的说法

TTypeError: data type not understood

用python在matlab文件中存储这样复杂的字典是不可能的吗?在


Tags: keyin数据结构fordatavalkeystemp
1条回答
网友
1楼 · 发布于 2024-04-24 21:03:53

编辑:答案(和问题有点)已经发生了显著的变化,变得更加普遍。如果询问者告诉我们backup中的值是什么类型的对象,这还是很有用的。在

在scipy.io.savemat显然可以取字典的数组,所以这个结构

from numpy import array
import scipy.io
data = {
    'bigdata' : {
        'a' : array([1, 2, 3]),
        'b' : array([1, 2, 3]),
        'c' : array([1, 2, 3]),
     }
}
scipy.io.savemat('test.mat', data)

加载到matlab as中

^{pr2}$

我认为这些字典可以嵌套到python的递归限制,因为实现是递归的。我测试了6个层次的嵌套字典。 编辑:现在你要问的是这样一个结构:

data = {
    'key1' : ['a' : apple, 'b' : banana],
    'key2' : ['c' : crabapple, 'd' : dragonfruit],
    ...
    }

你还没有具体说明什么是苹果、香蕉等。这取决于您希望在Matlab对象中从这些Python对象中获取什么数据。我测试了一些类,比如str(转换为char数组)、set(无法转换为array)和list(如果是同构的,则是array,如果是字符串,则是一些数字)等。代码看起来很像duck-type-ish,所以如果这些对象有一个公共的数据保存接口,它应该可以通过;我在这里为matlab5版本提供一个most relevant bit的摘录:

def to_writeable(source)
    if isinstance(source, np.ndarray):
        return source
    if source is None:
        return None
    # Objects that have dicts
    if hasattr(source, '__dict__'):
        source = dict((key, value) for key, value in source.__dict__.items()
                      if not key.startswith('_'))
    # Mappings or object dicts
    if hasattr(source, 'keys'):
        dtype = []
        values = []
        for field, value in source.items():
            if (isinstance(field, basestring) and
                not field[0] in '_0123456789'):
                dtype.append((field,object))
                values.append(value)
        if dtype:
            return np.array( [tuple(values)] ,dtype)
        else:
            return None
    # Next try and convert to an array
    narr = np.asanyarray(source)
    if narr.dtype.type in (np.object, np.object_) and \
       narr.shape == () and narr == source:
        # No interesting conversion possible
        return None
    return narr

相关问题 更多 >