简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM