gpt4 book ai didi

matlab - 连接元胞数组中结构的(子)字段

转载 作者:行者123 更新时间:2023-12-02 09:28:18 25 4
gpt4 key购买 nike

我有一个 Matlab 对象,它是一个包含具有几乎相同结构的结构的元胞数组,我想以编程方式获取所有元胞数组元素的结构的(子)字段。

例如,我们采取测试

test = {struct('a',struct('sub',1)), struct('a',struct('sub',2),'b',1)};

这将创建一个具有以下结构的元胞数组:

cell-element 1: a --> sub --> 1
cell-element 2: a --> sub --> 2
\-> b --> 1

可以看出,test的元素结构并不完全相同,而是相似。如何获取单元格元素的 a.sub 字段的所有值。我可以在这个特定问题中获得它们

acc=zeros(1,numel(test));
for ii=1:numel(test)
acc(ii) = test{ii}.a.sub;
end

但我无法完全让这个方法在更一般的上下文中工作(即具有不同的字段)。

最佳答案

您可能想使用函数getfield:

%//Data to play with
test = {struct('a',struct('sub',1)), struct('a',struct('sub',2),'b',1)};

%//I'm interested in these nested fields
nested_fields = {'a', 'sub'};

%//Scan the cell array to retrieve the data array
acca = cellfun(@(x) getfield(x, nested_fields{:}), test);

如果您的数据无法保证所有元素具有相同的类型和大小,那么您需要输出元胞数组:

%//Scan the cell array to retrieve the data cell array
accc = cellfun(@(x) getfield(x, nested_fields{:}), test, 'UniformOutput', false);

稍后编辑

如果想为每个单元格元素使用不同的嵌套字段集,则:

%//nested_fields list should have the same size as test
nested_fields = {{'a','sub'}, {'b'}};
accm = cellfun(@(x,y) getfield(x,y{:}), test, nested_fields, 'UniformOutput', false);

关于matlab - 连接元胞数组中结构的(子)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35626141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com