unique — Return unique elements or rows with MATLAB-compatible ordering and index mappings.
unique(A) removes duplicates and returns distinct elements or rows. It supports MATLAB-compatible sorted/stable ordering plus optional index outputs linking original and unique values.
Syntax
C = unique(A)
C = unique(A, option...)
[C, ia] = unique(A)
[C, ia] = unique(A, option...)
[C, ia, ic] = unique(A)
[C, ia, ic] = unique(A, option...)Inputs
A- Type
Any- Required
- Yes
- Description
- Input array.
option- Type
Any- Required
- Variadic
- Description
- Option tokens plus the 'TreatMissingAsDistinct', logical name-value pair.
Returns
C- Type
Any- Description
- Unique values or rows.
ia- Type
NumericArray- Description
- Indices selecting representatives in input A.
ic- Type
NumericArray- Description
- Indices mapping each input element/row to C.
Returned values from unique depend on how many outputs the caller requests.
Errors
RunMat:unique:LegacyOptionUnsupported- When
- Legacy compatibility options are requested.
- Message
unique: the 'legacy' behaviour is not supported
RunMat:unique:ConflictingOrderOptions- When
- Both 'sorted' and 'stable' options are provided.
- Message
unique: cannot combine 'sorted' with 'stable'
RunMat:unique:ConflictingOccurrenceOptions- When
- Both 'first' and 'last' options are provided.
- Message
unique: cannot combine 'first' with 'last'
Behavior
unique(A) flattens numeric, logical, character, string, or complex arrays column-major into a vector of unique values sorted ascending.
[C, IA] = unique(A) also returns the indices of the selected occurrences (IA) so that C = A(IA).
[C, IA, IC] = unique(A) provides IC, the mapping from each element of A to the corresponding index in C.
unique(A, 'stable') preserves the first appearance order rather than sorting.
unique(A, 'rows') treats each row as an observation and returns a matrix (or char/string array) whose rows are unique.
unique(A, 'last') or 'first' controls which occurrence contributes to IA (defaults to 'first').
Combinations such as unique(A, 'rows', 'stable', 'last') follow MATLAB's precedence rules; mutually exclusive flags (e.g. 'sorted' with 'stable') are rejected.
Empty inputs return empty outputs with consistent dimensions.
Legacy switches such as 'legacy' or 'R2012a' are not supported; RunMat does not implement the legacy flag forms.
Types, placement and limitations
Values retain their native numeric, logical, character or string class. Element results preserve row-vector orientation; other element results are columns. IA and IC are double columns. TreatMissingAsDistinct defaults to true; false groups missing values. Resident values and indices are restored to their input owner. Resident 64-bit integer inputs and explicit order combined with explicit occurrence selection are not supported.
Resident execution
These operations are eager fusion boundaries, not elementwise kernels or reductions, and do not broadcast. Provider availability does not imply a device-native sorting or set kernel: current providers may stage host work. An unsupported input can use exact host fallback before provider work starts. Errors after an attempt, including cancellation, are returned without repeating the operation on the host. Supported resident outputs return to their owning provider; predicates and all-indices cells have the host placement described above. Distributed execution is not supported.
Examples
Getting Sorted Unique Values
A = [3 1 3 2];
C = unique(A)Preserving Input Order with 'stable'
A = [4 2 4 1 2];
C = unique(A, 'stable')Returning Indices for Reconstruction
A = [7 5 7 3];
[C, IA, IC] = unique(A);
reconstructed = C(IC)Finding Unique Rows in a Matrix
A = [1 3; 1 3; 2 4; 1 2];
[C, IA, IC] = unique(A, 'rows')Expected output:
C =
1 2
1 3
2 4
IA =
4
1
3
IC =
2
2
3
1Selecting Last Occurrences
A = [9 8 9 7 8];
[C, IA] = unique(A, 'last')Working with Empty Arrays
A = zeros(0, 3);
[C, IA, IC] = unique(A, 'rows')Expected output:
C =
IA =
IC =Using unique on GPU Arrays
G = gpuArray([5 3 5 1]);
[C, IA, IC] = unique(G, 'stable')Unique Characters in a Char Array
chars = ['m','z'; 'm','a'];
[C, IA] = unique(chars)Expected output:
C =
a
m
z
IA =
4
1
3Unique Strings with Row Deduplication
S = ["alpha" "beta"; "alpha" "beta"; "gamma" "beta"];
[C, IA, IC] = unique(S, 'rows', 'stable')Expected output:
C =
2x2 string array
"alpha" "beta"
"gamma" "beta"
IA =
1
3
IC =
1
1
2Using unique with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how unique changes the result.
Run a small unique example, explain the result, then change one input and compare the output.
FAQ
Which ordering does unique use by default?⌄
Results are sorted in ascending order unless you pass 'stable', which preserves the first occurrence order.
How are the index outputs defined?⌄
IA indexes into the original data (or rows). IC is a column vector mapping each element (or row) of the input to the position of the corresponding unique value in C.
What do 'first' and 'last' control?⌄
They determine whether IA references the first or last occurrence of each distinct value/row. They do not affect C or IC.
Can I combine 'rows' with 'stable' or 'last'?⌄
Yes. All permutations of 'rows', 'stable'/'sorted', and 'first'/'last' are accepted. Conflicting flags are rejected; GPU combinations have the limitations described above.
Does unique support complex numbers or characters?⌄
Yes. Complex values use magnitude ordering for the sorted output, and character or string arrays produce results in their native container types (char arrays and string arrays respectively).
How does unique treat NaN values?⌄
NaNs are distinct by default. TreatMissingAsDistinct=false groups missing values. Sorted output places NaNs last; stable output follows input occurrence order.
Are GPU arrays supported?⌄
Values retain their native numeric, logical, character or string class. Element results preserve row-vector orientation; other element results are columns. IA and IC are double columns. TreatMissingAsDistinct defaults to true; false groups missing values. Resident values and indices are restored to their input owner. Resident 64-bit integer inputs and explicit order combined with explicit occurrence selection are not supported. These operations are eager fusion boundaries, not elementwise kernels or reductions, and do not broadcast. Provider availability does not imply a device-native sorting or set kernel: current providers may stage host work. An unsupported input can use exact host fallback before provider work starts. Errors after an attempt, including cancellation, are returned without repeating the operation on the host. Supported resident outputs return to their owning provider; predicates and all-indices cells have the host placement described above. Distributed execution is not supported.
Does unique preserve array shape?⌄
Element results preserve row-vector orientation and otherwise are columns. Row results retain the input column count.
What happens with empty inputs?⌄
Empty inputs (including empty matrices) return empty outputs with matching dimensions, and index outputs are empty column vectors.
Is unique stable?⌄
Sorting is stable where applicable; ties preserve their relative order. You can also request 'stable' explicitly.
Related Array functions
Sorting Sets
argsort · intersect · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sort · sortrows · union
Accumulation
Shape
blkdiag · cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · shiftdim · squeeze · toeplitz · tril · triu · vertcat
Creation
colon · createArray · empty · eye · false · full · inf · int16.empty · int32.empty · int64.empty · int8.empty · linspace · logspace · magic · meshgrid · nan · ndgrid · nonzeros · ones · peaks · rand · randi · randn · randperm · range · sparse · spdiags · speye · spones · sprand · true · uint16.empty · uint32.empty · uint64.empty · uint8.empty · zeros
Combinatorics
Binning
Grouping
Source you can read
Every RunMat function's source is public. Read exactly how unique is executed, line by line, in Rust.
- View the source for unique in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.