Tutorial :How can I find unique rows in a matrix, with no element order within each row?



Question:

I have an array comprising n rows and 4 colums. Each of the four entries on the row is an integer, i.e.,

X = [         111 112 432   2           6   9 115 111         112 432 111   2        ];   

Each row represents the vertices of a tetrahedron. These vertices have no directionality thus, in the case above, the tetrahedra represented by X(1,:) and X(3,:) are equivalent.

I wish to remove duplicate tetrahedra from X, but can't quite figure how to incorporate the order independence into my code.

I tried the UNIQUE() function but this returns a (nx1) array of unique integers, i.e.,

Y = UNIQUE(X);    Y = [       2       6       9       111       112       115       432      ]  

Anyone have any suggestions for a reasonably efficient way to complete this task?

Thanks, S :-)


Solution:1

First, sort the rows of your matrix to arrive at a "canonical" representation for the tetrahedra:

X = sort(X, 2);  

Then, use unique with the optional 'rows' argument to find unique rows:

Y = unique(X, 'rows');  


Solution:2

unique() will work on rows, but rows 1 and 3 are a different order. So we could sort them prior to using unique.

Y=unique(sort(X,2),'rows')    Y =         2   111   112   432       6     9   111   115  

If you want to retain the original ordering then unique will return the indices

[Y,yi]=unique(sort(X,2),'rows');    >> X(yi,:)    ans =       112   432   111     2       6     9   115   111  


Solution:3

To quote from the documentation:

b = unique(A, 'rows') returns the unique rows of A.

Is that what you want ?


Solution:4

you should sort the rows first, then use unique(A,'rows') as HPM suggests


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »