unique - Find unique elements of vector

Syntax

b = unique(A)
b = unique(A, 'rows')
[b, m, n] = unique(...)
[b, m, n] = unique(..., occurrence)

Description

b = unique(A) returns the same values as in A but with no repetitions. A can be a numeric or character array or a cell array of strings. If A is a vector or an array, b is a vector of unique values from A. If A is a cell array of strings, b is a cell vector of unique strings from A. The resulting vector b is sorted in ascending order and its elements are of the same class as A.

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

[b, m, n] = unique(...) also returns index vectors m and n such that b = A(m) and A = b(n). Each element of m is the greatest subscript such that b = A(m). For row combinations, b = A(m,:) and A = b(n,:).

[b, m, n] = unique(..., occurrence), where occurrence can be

If you do not specify occurrence, it defaults to 'last'.

You can specify 'rows' in the same command as 'first' or 'last'. The order of appearance in the argument list is not important.

Examples

A = [1 1 5 6 2 3 3 9 8 6 2 4] 
A = 
   1   1   5   6   2   3   3   9   8   6   2   4

Get a sorted vector of unique elements of A. Also get indices of the first elements in A that make up vector b, and the first elements in b that make up vector A:

[b1, m1, n1] = unique(A, 'first') 
b1 = 
   1   2   3   4   5   6   8   9 
m1 =  
   1   5   6  12   3   4   9   8 
n1 = 
   1   1   5   6   2   3   3   8   7   6   2   4

Verify that b1 = A(m1) and A = b1(n1):

all(b1 == A(m1)) && all(A == b1(n1)) 
ans = 
     1

Get a sorted vector of unique elements of A. Also get indices of the last elements in A that make up vector b, and the last elements in b that make up vector A:

[b2, m2, n2] = unique(A, 'last') 
b2 = 
   1   2   3   4   5   6   8   9 
m2 = 
   2  11   7  12   3  10   9   8 
n2 = 
   1   1   5   6   2   3   3   8   7   6   2   4

Verify that b2 = A(m2) and A = b2(n2):

all(b2 == A(m2)) && all(A == b2(n2)) 
ans = 
    1

Because NaNs are not equal to each other, unique treats them as unique elements.

unique([1 1 NaN NaN]) 
ans = 
    1 NaN NaN

See Also

intersect, ismember, sort, issorted, setdiff, setxor, union

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS