Removing rows that are not unique from an array?

조회 수: 28 (최근 30일)
John Jendzurski
John Jendzurski 2017년 7월 7일
편집: Jan 2017년 7월 8일
Is there an easy way to remove ALL rows that are NOT unique? For example, how would I get B from A?
A = [1 2; 1 3; 1 4; 1 2; 1 5];
B = [1 3; 1 4; 1 5];
I could do this in a loop, but there seems like there must be a more elegant way. I've looked at various applications in the forum using the unique() function, but a solution is not obvious to me.
Thanks!

채택된 답변

Star Strider
Star Strider 2017년 7월 7일
This works:
A = [1 2; 1 3; 1 4; 1 2; 1 5];
[~,ia,ic] = unique(A, 'rows'); % Unique Elements
v = accumarray(ic, 1); % Tally Occurrences Of Rows
B = A(ia(v==1),:) % Keep Rows That Only Appear Once
B =
1 3
1 4
1 5
  댓글 수: 5
John Jendzurski
John Jendzurski 2017년 7월 8일
Thank you, Star Strider. This looks perfect. I was not aware of the accumarray() function...until now!
Star Strider
Star Strider 2017년 7월 8일
As always, my pleasure.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2017년 7월 7일
편집: Jan 2017년 7월 8일
As = sortrows(A);
k = find([true; any(diff(As, 1, 1), 2); true]);
B = As(k(diff(k) == 1), :);
And if the original order is wanted:
[As, idx1] = sortrows(A);
k = find([true; any(diff(As, 1, 1), 2); true]);
idx2 = k(diff(k) == 1);
B = A(idx1(idx2), :);
For A = randi([1, 20], 1e5, 4) the first method is 15% faster than the unique/accumarray method.
  댓글 수: 3
Image Analyst
Image Analyst 2017년 7월 8일
This is asked so often it should be in the FAQ. But before I do, I'd like to have a solution to the other case people ask a lot about, and that is where people want to keep the first instance of the duplicate row (along with unique rows), rather than toss out all rows that are members of duplicates. Another case might be to keep only the duplicate rows.
Jan
Jan 2017년 7월 8일
편집: Jan 2017년 7월 8일
Isn't "keeping the first instance" solved by
unique(A, 'rows', 'first')
And for keeping the multiple occuring rows only use:
As = sortrows(A);
k = find([true; any(diff(As, 1, 1), 2); true]);
B = As(k(diff(k) > 1), :);
% ^ instead of ==

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by