考虑到MatLab结构,我在字段名上有一个循环如下:
scenario = fieldnames(myStruct)
for scenarioidx = 1:length(scenario)
scenarioname = scenario{scenarioidx};
category = fieldnames(myStruct.(scenarioname))
for categoryidx = 1:length(category)
categoryname = category{categoryidx};
entity = fieldnames(myStruct.(scenarioname).(categoryname))
end
end
此循环返回每个类别的实体。现在,我想将所有这些实体组合在一个向量中。我试图使用' union'功能如下:
scenario = fieldnames(myStruct)
for scenarioidx = 1:length(scenario)
scenarioname = scenario{scenarioidx};
category = fieldnames(myStruct.(scenarioname))
for categoryidx = 1:length(category)
categoryname = category{categoryidx};
allEntity = {}
entity = fieldnames(myStruct.(scenarioname).(categoryname))
combo_entity = union (allEntity, entity)
end
end
不幸的是,这只是返回与之前相同的结果而不是任何组合。 有没有人对如何在这样的循环中实现union函数有任何想法?
答案 0 :(得分:1)
简单地:
struct_entities = structfun(@struct2cell, myStruct, 'UniformOutput', false);
cell_entities = struct2cell(struct_entities);
all_entities = unique(vertcat(cell_entities{:}));
这个想法是:
如果需要使用union,则代码可能会被重写为:
all_entities = {};
scenarios = fieldnames(myStruct);
for si = 1:numel(scenarios)
categories = fieldnames(myStruct.(scenarios{si}));
for ci = 1:numel(categories)
entities = fieldnames(myStruct.(scenarios{si}).(categories{ci}));
all_entities = union(all_entities, entities);
end;
end;