Reputation: 1373
If i want to find the union of two unordered sets, represented as 1D vectors, eg:
a = [2 4 6 8 1]
b = [1 2 5 7 9]
i can use the union function:
c = union(a,b)
which gives the answer:
c = [1 2 4 5 6 7 8 9]
however, this appears to be quite slow (relatively speaking). If i run a tic-toc test on it i get:
>> for test = 1
tic
c = union(a,b);
toc
end
Elapsed time is 0.000906 seconds.
whereas, if i use this much more convoluted method, i get a much quicker result:
>> for test = 1
tic
a_1 = zeros(1,9);
b_1 = zeros(1,9);
a_1(a) = 1;
b_1(b) = 1;
c_1 = or(a_1,b_1);
c = find(c_1);
toc
end
Elapsed time is 0.000100 seconds.
this still gives the same answer for c, but is about 9 times as fast (with this small example, im not sure about how well it scales)
what is the advantage of ever using union? and can anyone suggest a more compact way of expressing the second method that i used?
thanks
Upvotes: 1
Views: 601
Reputation: 4519
Several comments:
Upvotes: 5