使用MatLab' Union'循环中的函数

时间:2015-08-26 14:59:13

标签: matlab loops union

考虑到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函数有任何想法?

1 个答案:

答案 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;