Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eliminate repeated vectors but with elements on different order

I have a matrix A which is (243 x 5). I want to pick the unique row vectors of that matrix but taking into account that row vectors with the same elements but in different order shall be considered as being the same.

E.g., suppose for simplicity that the A matrix is (10 x 5) and equal to:

 A=[1   2   1   2   3
    1   3   1   1   1
    1   3   1   1   2
    1   2   1   1   3
    2   3   1   2   1
    1   3   1   2   2
    1   3   1   2   3
    1   3   1   3   2
    1   3   1   3   1
    1   3   2   3   1]

On the example above, rows (1, 5, 6) are to be considered equivalent they have the same elements but in different order. Also, rows (3 and 4) are equivalent, and rows (7, 8, 10) are also equivalent.

Is there any way to write a code that removes all "repeated rows", i.e. a code that delivers only the rows (1, 2, 3, 7 and 9) from A?

So far I came across with this solution:

B(:,1) = sum(A == 1,2);
B(:,2) = sum(A == 2,2);
B(:,3) = sum(A == 3,2);
[C, ia, ic] = unique(B,'rows');
Result = A(ia,:);

This delivers what I am looking for with one caveat - it is delivering the unique rows of A according to the criteria defined above, but it is not delivering the first row it finds. I.e. instead of delivering rows (1,2,3,7,9) it is delivering rows(7, 1, 9, 3, 2).

Anyway I can force him to deliver the rows in correct order? Also any better way of doing this?

like image 603
phdstudent Avatar asked Dec 05 '25 07:12

phdstudent


1 Answers

You can do it as follows:

  1. Sort A along the second dimension;
  2. Get stable indices of unique (sorted) rows;
  3. Use the result as row indices into the original A.

That is:

As = sort(A, 2);
[~, ind] = unique(As, 'rows', 'stable');
result = A(ind,:);

For

A = [1   2   1   2   3
     1   3   1   1   1
     1   3   1   1   2
     1   2   1   1   3
     2   3   1   2   1
     1   3   1   2   2
     1   3   1   2   3
     1   3   1   3   2
     1   3   1   3   1
     1   3   2   3   1];

this gives

result =
     1     2     1     2     3
     1     3     1     1     1
     1     3     1     1     2
     1     3     1     2     3
     1     3     1     3     1
like image 170
Luis Mendo Avatar answered Dec 07 '25 22:12

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!