steve
steve

Reputation: 531

Using MatLab 'Union' function in a loop

Considering a MatLab struct, I have a loop over fieldnames as follow:

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

This loop returns me entities for each categories. Now, I would like to combine all those entities in one vector. I tried to used the 'union' function as follow:

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

Unfortunately, this is just returning the same results as previously and not combine anything. Does anyone has any ideas about how to implement the union function in such a loop?

Upvotes: 0

Views: 211

Answers (1)

user2271770
user2271770

Reputation:

Simply:

struct_entities = structfun(@struct2cell, myStruct, 'UniformOutput', false);
  cell_entities = struct2cell(struct_entities);
   all_entities = unique(vertcat(cell_entities{:}));

The idea is to:

  • retrieve the entities and give up the category names;
  • give up the scenario names too, because they're not needed;
  • assemble the accumulated entities in a single cell array.

If the use of union is required, then the code may be rewritten as:

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;

Upvotes: 1

Related Questions