Check common elements in two vectors and remove them from both the vectors leaving any duplicate. (Example Inside)
21 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (3)
KSSV
am 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 Kommentare
David Wilson
am 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.
Guillaume
am 24 Apr. 2019
Bearbeitet: Guillaume
am 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)
0 Kommentare
Andrei Bobrov
am 24 Apr. 2019
Bearbeitet: Andrei Bobrov
am 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));
0 Kommentare
Siehe auch
Kategorien
Mehr zu Entering Commands finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!