[37] | 1 | function [c,a_match,b_match] = union_sorted(a,b)
|
---|
| 2 | %UNION_SORTED Set union of sorted sets.
|
---|
| 3 | % UNION_SORTED(A,B) where A and B are vectors returns the combined values
|
---|
| 4 | % from A and B with no repetitions. A (and B) must be sorted and unique, and
|
---|
| 5 | % the result will be sorted and unique.
|
---|
| 6 | %
|
---|
| 7 | % [C,A_MATCH,B_MATCH] = UNION_SORTED(A,B) also returns
|
---|
| 8 | % A_MATCH = MATCH_SORTED(A,C)
|
---|
| 9 | % B_MATCH = MATCH_SORTED(B,C)
|
---|
| 10 | %
|
---|
| 11 | % Examples:
|
---|
| 12 | % union_sorted([20 30 40], [10 20 30])
|
---|
| 13 | % [c,a_match,b_match] = union_sorted([20 30 40], [10 20 30])
|
---|
| 14 |
|
---|
| 15 | % Written by Tom Minka
|
---|
| 16 | % (c) Microsoft Corporation. All rights reserved.
|
---|
| 17 |
|
---|
| 18 | % instead of a full sort, you could do a merge of the two sorted lists.
|
---|
| 19 | if nargout <= 1
|
---|
| 20 | c = sort([a(~ismember_sorted(a,b)) b]);
|
---|
| 21 | else
|
---|
| 22 | [tf,loc] = ismember_sorted(a,b);
|
---|
| 23 | [c,i] = sort([a(~tf) b]);
|
---|
| 24 | % c = [a(~tf) b](i)
|
---|
| 25 | nc = length(c);
|
---|
| 26 | nb = length(b);
|
---|
| 27 | na = length(a);
|
---|
| 28 | index = zeros(1,nc);
|
---|
| 29 | index(i) = 1:nc;
|
---|
| 30 | % c(index) = [a(~tf) b]
|
---|
| 31 | b_match = index((nc-nb+1):nc);
|
---|
| 32 | a_match = zeros(1,na);
|
---|
| 33 | a_match(~tf) = index(1:(nc-nb));
|
---|
| 34 | a_match(tf) = b_match(loc(tf));
|
---|
| 35 | end
|
---|