Calculate the union of multiple array cells in matlab

I have an array of cells where each element consists of a vector of identifiers. I like to compute the union of all the elements in an array of cells. This is my current solution, but I feel that it can be vectorized or have a more elegant solution:

union_ids = union(encounter_ids{1},encounter_ids{2});
for i=3:1:numel(encounter_ids);
    union_ids = union(union_ids,encounter_ids{i});
end
+3
source share
1 answer

If the elements of the cell array are row vectors, you can do this:

union_ids = unique( [encounter_ids{:}] );

if they are column vectors, use:

union_ids = unique( vertcat(encounter_ids{:}) );

If you're not sure if they are both (some are row vectors, some are columns), you can make them be all column vectors:

encounter_ids = cellfun(@(c)c(:), encounter_ids, 'UniformOutput',false);
union_ids = unique( vertcat(encounter_ids{:}) );
+6
source

Source: https://habr.com/ru/post/1760193/


All Articles