views:

35

answers:

1

I have a cell array where each element consists of a vector of ids. I like to compute the union of all elements in the cell array. This is my current solution, but I feel 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  A: 

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

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

instead if they are column vectors, then use:

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

If you are unsure, or they happen to be both (some are row vectors, some are columns), then you can force them to be all column vectors:

encounter_ids = cellfun(@(c)c(:), encounter_ids, 'UniformOutput',false);
union_ids = unique( vertcat(encounter_ids{:}) );
Amro
??? Error using ==> horzcatCAT arguments dimensions are not consistent.
Elpezmuerto

related questions