Check common elements in two vectors and remove them from both the vectors leaving any duplicate. (Example Inside)

52 views (last 30 days)
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.

Answers (3)

KSSV
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)

Guillaume
Guillaume on 24 Apr 2019
Edited: Guillaume on 24 Apr 2019
"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
Andrei Bobrov on 24 Apr 2019
Edited: Andrei Bobrov on 24 Apr 2019
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 Characters and Strings 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!