How to find rows with multiple entries that are equal?

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.

 Risposta accettata

Kirby Fears
Kirby Fears il 6 Ott 2015
Modificato: Kirby Fears il 6 Ott 2015
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.

Più risposte (2)

the cyclist
the cyclist il 6 Ott 2015
Modificato: the cyclist il 6 Ott 2015
A(sum(diff([nan(size(A,1),1),sort(A,2)],1,2)==0,2)==(size(A,2)-2),:)
out = A(any(hist(A')==3),:);

1 Commento

Thank you. Needs the correction below though.
M=size(A,2);
out= A(~any(hist(A')==(M),:);

Accedi per commentare.

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by