如何从scipy.io创建Matlab结构数组? [英] How can I create a Matlab struct array from scipy.io?

查看:141
本文介绍了如何从scipy.io创建Matlab结构数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下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中(

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})

但是,当尝试将其推广到结构 array 时,我遇到了以下障碍:

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 数组,而不是struct数组.

This does not behave as expected; when loading p.mat into Matlab, I get a 1x2 cell array, not a struct array.

  1. 我尝试了savemat('/tmp/p.mat', np.array(struct_array))savemat('/tmp/p.mat', np.array(struct_array, dtype=object)),但无济于事.
  1. I have tried savemat('/tmp/p.mat', np.array(struct_array)) and savemat('/tmp/p.mat', np.array(struct_array, dtype=object)), to no avail.

推荐答案

您可以使用np.core.records.fromarrays构造一个记录数组,该数组大致等效于MATLAB结构,并且将由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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆