Find unique cell vector values ​​without sorting the result

I have a row vector

          x = {'rrr' 'aaa' 'bbb' 'hhh' 'aaa' 'ppp'};
          y = unique(x);

This code returns a unique value, but sorts it. Output of this code

          y = {'aaa' 'bbb' 'hhh' 'ppp' 'rrr'}

I want it to return unique values, but not sorted. The output I want is

          y =  {'rrr' 'aaa' 'bbb' 'hhh' 'ppp'}

How to do it?

+3
source share
3 answers

You can use the second output argument unique, which returns the index of unique elements. To display them in their original order, use the function sortin the index vector before indexing the original vector.

 x = {'rrr' 'aaa' 'bbb' 'hhh' 'aaa' 'ppp'};
 [y,i] = unique(x);

 x(sort(i)) 

Output:

ans = 

    'rrr'    'bbb'    'hhh'    'aaa'    'ppp'
+4
source

This blog post explains this very well:

    [X, SortVec] = sort(x);
    %Remove duplicates
    UV(SortVec) = ([1; diff(X)] ~= 0);
    %Resort to be back in original order
    y = B(UV);
+3
source

MATLAB, R2012a, unique, , . @HMuster @Dan .

+3

All Articles