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

53 visualizzazioni (ultimi 30 giorni)
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.

Risposte (3)

KSSV
KSSV il 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 Commenti
Edoardo Busetti
Edoardo Busetti il 24 Apr 2019
This doesn't do it, it deletes values that appear one time in a vector but multiple times in the other
David Wilson
David Wilson il 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.

Accedi per commentare.


Guillaume
Guillaume il 24 Apr 2019
Modificato: Guillaume il 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 il 24 Apr 2019
Modificato: Andrei Bobrov il 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));

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by