Angelababy
Angelababy

Reputation: 243

The union of several vectors

I have three vectors, v1, v2, and v3, each of which has 500 values. The three vectors may or may not have the same values. I want to know how to get the union set of the three vectors. If they have same values, the value can only be dislayed once in the union set.

Upvotes: 0

Views: 3931

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112689

You can apply unique to the concatenation (cat) of all vectors. This allows an arbitrary number of vectors, using a comma-separated list generated from a cell array containing all vectors. All vectors are assumed to have the same, known orientation (they are all row vectors, or all column vectors).

vectors = {[1 4 3 2], [4 5 6], [5 1 8], [4 8]};  %// row vectors
result = unique(cat(2, vectors{:}));             %// change "2" to "1" for column vectors

Upvotes: 2

horchler
horchler

Reputation: 18484

You can do it with a single call to union:

% Create random example data
rng(1);
v1  = randi(1000,[1 500]);
v2  = randi(1000,[1 500]);
v3  = randi(1000,[1 500]);

v_union = union([v1(:);v2(:)],v3)

Upvotes: 4

Related Questions