Check common elements in two vectors and remove them from both the vectors leaving any duplicate. (Example Inside)
52 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(3 个)
KSSV
2019-4-24
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 个评论
David Wilson
2019-4-24
Is this correct though? You've dropped all the 4's, I think the original poster only wanted one dropped in new_A.
Guillaume
2019-4-24
编辑:Guillaume
2019-4-24
"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 个评论
Andrei Bobrov
2019-4-24
编辑:Andrei Bobrov
2019-4-24
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!