I have a NxM matrix and I want to find the rows that have M-1 duplicate entries. For example:
A=[1 1 2 4;
2 2 2 1;
2 9 3 0;
3 0 3 3;
4 3 2 2];
fun(A);
ans = [2 2 2 1;
3 0 3 3]
How could I do this, preferably elegantly in a few lines? I am trying to avoid loops because I anticipate working with large matrices eventually.

 채택된 답변

Kirby Fears
Kirby Fears 2015년 10월 6일
편집: Kirby Fears 2015년 10월 6일
In two lines:
sA=sort(A,2);
A(sum(sA(:,2:end)==sA(:,1:end-1),2)==size(sA,2)-2,:)
ans =
2 2 2 1
3 0 3 3
Here's another method that doesn't use sort(). It's slightly faster for large matrices on my machine:
rowIdx=(sum(repmat(A(:,1),1,size(A,2))~=A,2)==1) | ...
(sum(repmat(A(:,2),1,size(A,2))~=A,2)==1);
A=A(rowIdx,:);
You might want to break that down into more lines of code for readability.
Hope this helps.

추가 답변 (2개)

the cyclist
the cyclist 2015년 10월 6일
편집: the cyclist 2015년 10월 6일
A(sum(diff([nan(size(A,1),1),sort(A,2)],1,2)==0,2)==(size(A,2)-2),:)
Andrei Bobrov
Andrei Bobrov 2015년 10월 6일
out = A(any(hist(A')==3),:);

댓글 수: 1

Colton
Colton 2015년 10월 6일
편집: Colton 2015년 10월 6일
Thank you. Needs the correction below though.
M=size(A,2);
out= A(~any(hist(A')==(M),:);

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

질문:

2015년 10월 6일

편집:

2015년 10월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by