如何从 scipy.io 创建一个 Matlab 结构数组? [英] How can I create a Matlab struct array from scipy.io?
问题描述
考虑以下 Matlab 代码:
Consider the following Matlab code:
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
中有以下层次结构:
This creates a struct array. Each struct in the array contains three fields of type cell
. As such, we have the following hierarchy in 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).
I'm trying to use scipy.io
to produce the above data structures in Python, such that they can be loaded into Matlab (this hierarchy is required by SPM).
创建一个结构体很简单,因为scipy.io.savemat
将任何键都是 str
类型的字典保存为一个 Matlab 结构体:
Creating a struct is straightforward, as scipy.io.savemat
saves any dict whose keys are all of type str
as a Matlab struct:
from scipy.io import savemat
struct = {
'field1': 1,
'field2': 2,
}
savemat('/tmp/p.mat', {'a_struct': struct})
然而,当试图将其推广到结构数组时,我遇到了以下障碍:
However, when trying to generalize this to a struct array, I hit the following roadblock:
struct_array = [struct, struct]
savemat('/tmp/p.mat', {'s_array': struct_array})
这不符合预期;将 p.mat
加载到 Matlab 中时,我得到一个 1x2 cell 数组,而不是结构数组.
This does not behave as expected; when loading p.mat
into Matlab, I get a 1x2 cell array, not a struct array.
- 我试过
savemat('/tmp/p.mat', np.array(struct_array))
和savemat('/tmp/p.mat', np.array(struct_array, dtype=object))
,无济于事.
- I have tried
savemat('/tmp/p.mat', np.array(struct_array))
andsavemat('/tmp/p.mat', np.array(struct_array, dtype=object))
, to no avail.
推荐答案
你可以使用 np.core.records.fromarrays
来构造一个记录数组,大致相当于一个 MATLAB struct,并且将通过 scip.io.savemat
转换为 MATLAB 结构体.
You can use np.core.records.fromarrays
to construct a record array, which is roughly equivalent to a MATLAB struct, and will be converted to a MATLAB struct by scip.io.savemat
.
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 中打开时,这给出:
When opened in MATLAB, this gives:
>> load('p.mat')
>> myrec
myrec =
1x2 struct array with fields:
field1
field2
这篇关于如何从 scipy.io 创建一个 Matlab 结构数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!