unique
Distinct values of an array, sorted, with optional index maps.
Category: Language Fundamentals > Data Types
Syntax
C = unique(A)
Returns the sorted distinct values of A.
C = unique(A, 'stable')
Keeps the order of first appearance instead of sorting.
[C, ia, ic] = unique(A)
Also returns index vectors: C = A(ia) and A = C(ic).
Description
unique removes repeated values. Numbers are sorted ascending and text alphabetically. Several NaN values are all counted as different, so each NaN is kept.
The third output ic is especially useful: accumarray(ic, 1) counts how many times each distinct value occurs.
Input arguments
A- Numeric, logical, char, string array, cell array of character vectors, categorical or table.
'stable'- Return values in the order they first appear.
Output arguments
C- The distinct values. For a row vector input the result is a row; for a cell array of text it is a column.
ia- Indices of the first occurrence of each value of
CinA. ic- Indices that rebuild
AfromC, one per element ofA. It is also a way to number groups.
Example
Values, indices and stable order
[u, i, j] = unique([3 1 1 2 3])
unique({'b','a','b'})
unique([3 1 1 2 3], 'stable')
Output
u = 1×3
1 2 3
i = 3×1
2
4
1
j = 5×1
3
1
1
2
3
ans = 2×1 cell
{'a'}
{'b'}
ans = 1×3
3 1 2