ntough
ntough

Reputation: 363

remove the rows in a matrix whose elements are the same in matlab

Given a 2-column matrix, for instance. The input is:

[ 1,2;
  3,4;
  5,5]

The expected output is:

[1,2;
 3,4;]

Does anyone know how do accomplish this? Many thanks for your time and attention.

Upvotes: 0

Views: 59

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

Your question suggests your matrix may have an arbitrary number of columns. In that case you may want to delete a row if it has (a) any two elements equal, or (b) all elements equal.

One possible approach is:

  1. Apply sort along each row;
  2. Use diff to compute differences between consecutive elements;
  3. Generate a logical index with all to (a) keep rows for which all such differences are non-zero, or with any to (b) keep rows for which any such difference is non-zero:

So:

X = [1 2 3;
     3 4 3;
     5 5 5];
Y = X(all(diff(sort(X,2),[],2),2),:);
Z = X(any(diff(sort(X,2),[],2),2),:);

gives

Y =
     1     2     3
Z =
     1     2     3
     3     4     3

Upvotes: 2

cwissy
cwissy

Reputation: 513

You could use logical indexing:

A = [1 2;3 4;5 5];
match = A(:,1) == A(:,2); // 1 where row has the same elements in both columns
A(match,:) = []; // make the match columns empty

You would need to make this more generic for another case, but for two columns and your example this will work.

Upvotes: 2

Related Questions