我有一个Matlab对象,它是一个包含结构几乎相同的结构的单元格数组,我想以编程方式获取所有单元格数组元素的结构的(子)字段。
例如,我们以 test
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句