Check common elements in two vectors and remove them from both the vectors leaving any duplicate. (Example Inside)
Show older comments
Suppose I have two vectors:
A = [1 2 3 4 4 4 5 5 6]
B = [2 4 5 5 9 ]
I want to get:
new_A = [1 3 4 4 6]
new_B = [9]
For example let's say that the vector A contains the elements of a numerator (1*2*3*4*4*4*5*5*6) and the vector B the elements of a denominator (2*4*5*5*9) and I want to simplify numerator and denominator.
2 Comments
David Wilson
on 24 Apr 2019
Try the intersect function and friends (such as setxor).
Edoardo Busetti
on 24 Apr 2019
Answers (3)
KSSV
on 24 Apr 2019
A = [1 2 3 4 4 4 5 5 6]
B = [2 4 5 5 9 ]
new_A = setdiff(A,B)
new_B = setdiff(B,A)
2 Comments
Edoardo Busetti
on 24 Apr 2019
David Wilson
on 24 Apr 2019
Is this correct though? You've dropped all the 4's, I think the original poster only wanted one dropped in new_A.
"Thank you, intersect did it"
intersect on its own will not do it since all set membership functions (setdiff, setxor, union, ismember, etc.) completely ignores duplicate elements.
You would have to compute the histogram of each to solve your problem and work out the intersection of that.
A = [1 2 3 4 4 4 5 5 6]
B = [2 4 5 5 9]
%get unique values of each set
uA = unique(A);
uB = unique(B);
%compute histogram of each set
countA = histcounts(A, [uA, Inf]);
countB = histcounts(B, [uB, Inf]);
%find common values of each set
[~, locA, locB] = intersect(uA, uB);
%minimum count of duplicate from each set
removecount = min(countA(locA), countB(locB));
%remove that minimum count from the total count in each set
countA(locA) = countA(locA) - removecount;
countB(locB) = countB(locB) - removecount;
%and recreate sets based on the new count
newA = repelem(uA, countA)
newB = repelem(uB, countB)
Andrei Bobrov
on 24 Apr 2019
Edited: Andrei Bobrov
on 24 Apr 2019
0 votes
a1 = unique([A(:);B(:)]);
s = size(a1);
[~,iA] = ismember(A(:),a1);
[~,iB] = ismember(B(:),a1);
ii = (accumarray(iA,1,s) - accumarray(iB,1,s)).*[1,-1];
ii = ii.*(ii > 0);
new_A = repelem(a1,ii(:,1));
new_B = repelem(a1,ii(:,2));
Categories
Find more on Time Series Events in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!