python - 使用python存储matlab文件

标签 python matlab scipy

我有一个复杂的数据结构

data = {}
temp = {}

data['bigdata'] = temp;

在此之后,我将一些其他数据结构中的“key”和“data”值复制到 temp 中,就像这样

for key in backup.keys():
    temp[key] = []

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 文件中吗?

最佳答案

编辑:答案(和问题有所不同)已发生重大变化,变得更加笼统。如果提问者告诉我们 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 为

>> load test.mat
>> bigdata

bigdata = 

    a: [3x1 int64]
    c: [3x1 int64]
    b: [3x1 int64]

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

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

而且您还没有具体说明苹果、香蕉等是什么。这取决于您希望在 Matlab 对象中使用这些 Python 对象的哪些数据。我测试了几个类,如 str(转换为 char 数组)、set(无法转换为数组)和 list(如果是同类数组,如果是一些字符串、一些数字则为字符数组)。代码看起来很像鸭子类型,所以如果这些对象有任何通用的数据保存接口(interface),它应该可以通过;我在这里摘录了 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

关于python - 使用python存储matlab文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7689958/

相关文章:

python - python 中分布的正态性检验

来自 "PBKDF2WithHmacSHA512"的 java 散列不同于 python CRYPT(digest_alg ='pbkdf2(1000,20,sha512)' , salt=True)(password)[0])

python - Python 中的身份集?

params 中 param 的 python 语法

python - 协同尾部旋转

matlab - 将字符串数组转换为单元格

c++ - 如何将 C++ 连接到 Matlab

database - 在向量中搜索计算量太大

python - 使用第二个索引作为列将 Pandas 多索引系列转换为数据框

linux - libgfortran.so.1 : cannot open shared object file