考虑以下 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
中,我们有以下层次结构:
pmod // struct array
|
*- struct
| |
| *- cell // contains 1 or more strings
| *- cell // contains 1 or more arrays
| *- cell // contains 1 or more arrays
|
*- struct [...]
我正在尝试使用scipy.io
在Python中生成上述数据结构,以便它们可以加载到Matlab中(这种层次结构是SPM所需的)。
创建一个结构体很简单,因为scipy.io.savemat
将任何所有键都是str
类型的字典保存为Matlab结构体:
from scipy.io import savemat
struct = {
'field1': 1,
'field2': 2,
}
savemat('/tmp/p.mat', {'a_struct': struct})
然而,当我尝试将这个方法推广到结构体数组时,我遇到了以下障碍:
struct_array = [struct, struct]
savemat('/tmp/p.mat', {'s_array': struct_array})
加载p.mat
文件到Matlab时,出现了与预期不符的情况。我得到了一个1x2的cell数组,而不是结构体数组。
如何使用scipy.io
创建结构体数组?
注意事项:
- 我尝试过
savemat('/tmp/p.mat', np.array(struct_array))
和savemat('/tmp/p.mat', np.array(struct_array,dtype=object))
,但都无法解决问题。