Unique entries in a vector

| categories: miscellaneous | View Comments

unique_entries

Contents

Unique entries in a vector

John Kitchin

It is surprising how often you need to know only the unique entries in a vector of entries. Matlab provides the unique` to solve these problems. The :command:`unique command returns the sorted unique entries in a vector.

a = [1 1 2 3 4 5 3 5]

unique(a)
a =

     1     1     2     3     4     5     3     5


ans =

     1     2     3     4     5

The unique command also works with cell arrays of strings.

a = {'a'
    'b'
    'abracadabra'
    'b'
    'c'
    'd'
    'b'}

unique(a)
a = 

    'a'
    'b'
    'abracadabra'
    'b'
    'c'
    'd'
    'b'


ans = 

    'a'
    'abracadabra'
    'b'
    'c'
    'd'

There is more!

The unique command has some other features too. check them out:

help unique
 UNIQUE Set unique.
    B = UNIQUE(A) for the array A returns the same values as in A but
    with no repetitions. B will also be sorted. A can be a cell array of
    strings.
 
    UNIQUE(A,'rows') for the matrix A returns the unique rows of A.
 
    [B,I,J] = UNIQUE(...) also returns index vectors I and J such
    that B = A(I) and A = B(J) (or B = A(I,:) and A = B(J,:)).
 
    [B,I,J] = UNIQUE(...,'first') returns the vector I to index the
    first occurrence of each unique value in A.  UNIQUE(...,'last'),
    the default, returns the vector I to index the last occurrence.
 
    See also UNION, INTERSECT, SETDIFF, SETXOR, ISMEMBER, SORT, ISSORTED.

    Overloaded methods:
       cell/unique
       dataset/unique
       RTW.unique
       categorical/unique

    Reference page in Help browser
       doc unique

'done'

% categories: Miscellaneous
ans =

done

blog comments powered by Disqus