如何从西皮·欧?

2024-03-28 22:59:00 发布

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

考虑以下Matlab代码:

pmod(1).name{1}  = 'regressor1';
pmod(1).param{1} = [1 2 4 5 6];
pmod(1).poly{1}  = 1; 
pmod(2).name{1}  = 'regressor2-1';
pmod(2).param{1} = [1 3 5 7]; 
pmod(2).poly{1}  = 1;

这将创建一个结构数组。数组中的每个结构包含三个cell类型的字段。因此,我们在pmod中有以下层次结构:

^{pr2}$

我试图使用scipy.io在Python中生成上述数据结构,以便它们可以加载到Matlab中(这个层次结构是SPM所必需的)。在

创建一个结构很简单,因为scipy.io.savemat将所有键都是str类型的dict保存为一个Matlab结构:

from scipy.io import savemat

struct = {
    'field1': 1,
    'field2': 2,
}

savemat('/tmp/p.mat', {'a_struct': struct})

然而,当我试图将其推广到struct数组时,我遇到了以下障碍:

struct_array = [struct, struct]
savemat('/tmp/p.mat', {'s_array': struct_array})

这与预期不符;当将p.mat加载到Matlab中时,我得到的是1x2cell数组,而不是struct数组。在

如何使用scipy.io创建结构数组?在

注:

  1. 我试过savemat('/tmp/p.mat', np.array(struct_array))和{},但没有用。在

Tags: nameio类型paramscipy数组结构array
1条回答
网友
1楼 · 发布于 2024-03-28 22:59:00

您可以使用np.core.records.fromarrays来构造一个记录数组,它大致相当于一个MATLAB结构,它将由scip.io.savemat转换为MATLAB结构。在

from numpy.core.records import fromarrays
from scipy.io import savemat

myrec = fromarrays([[1, 10], [2, 20]], names=['field1', 'field2'])
savemat('p.mat', {'myrec': myrec})

在MATLAB中打开时,可以得到:

^{pr2}$

相关问题 更多 >