Written and maintained by CASRAI Editorial Board
Published
On this page
Researchers, data analysts, and computational scientists frequently encounter datasets containing redundant observations, duplicate sensor logs, and repeated experimental trials. In MATLAB, the unique function provides a native, vectorized mechanism to identify and extract distinct values from numerical arrays, matrices, cell arrays of character vectors, string arrays, tables, and timetables. Understanding how to configure sorting behavior, isolate unique matrix rows, track positional indices with index vectors (ia and ic), and accommodate missing data ensures robust, reproducible data processing pipelines.
What it is used for in research
In quantitative empirical workflows, raw data files often aggregate repeated records across multiple measurement batches, experimental runs, or distributed telemetry nodes. The MATLAB unique function (often searched by analysts as unique matlab) performs set deduplication while preserving mathematical traceability between raw input arrays and sanitized subsets. Primary research applications include:
- Experimental Trial Filtering: Isolating unique participant identifiers, test conditions, or experimental sessions from longitudinal multi-subject logs.
- Grid Coordinate Sanitization: Extracting distinct spatial coordinates or non-redundant time steps before numerical operations such as MATLAB interpolation, which strictly requires monotonically increasing or non-duplicate grid points.
- Subgroup Aggregation and Classification: Leveraging output index vectors to group repeated measurements, calculate categorical frequencies without procedural loops, and accelerate vectorized code architectures as outlined in our guide on MATLAB vectorize strategies.
- Multidimensional Matrix Deduplication: Filtering entire experimental observation rows where multiple measurements (e.g., [SubjectID, Timestamp, Treatment]) define record uniqueness.
- Data Curation and Provenance: Cleaning raw laboratory data tables for repository deposit and FAIR-compliant sharing, aligning with standards for research data curation.
Install or access (official source only)
MATLAB is commercial scientific computing software developed by The MathWorks, Inc. The unique function is a core MATLAB capability available across all base installations without requiring additional proprietary toolboxes (such as the Statistics and Machine Learning Toolbox). Researchers can access MATLAB through the following official channels:
- Institutional and Campus-Wide Licensing: Most university researchers and academic departments obtain access via institutional site licenses managed through the official MathWorks Account portal. Users log in with their institutional credentials at the MathWorks website to link their profile to their institution’s license.
- MathWorks Installer (Local Installation): Official installer packages for Windows (64-bit), macOS (Apple Silicon and Intel architectures), and Linux (Ubuntu, Red Hat Enterprise Linux, Debian, SUSE) can be downloaded directly from the official MathWorks Downloads portal (
https://www.mathworks.com/downloads/). - MATLAB Online: Full browser-based access is available at
https://matlab.mathworks.com, allowing researchers to run computational scripts and access cloud storage without local administrative privileges. - Command Environment: All examples below can be executed directly in the MATLAB Command Window (at the
>>prompt), within a MATLAB script (.mfile), or in a MATLAB Live Script (.mlx).
Step-by-step task
Follow these numbered steps to execute array and matrix deduplication, configure order preservation, and extract indexing vectors in MATLAB.
- Open the MATLAB Command Window or Editor: Launch your local MATLAB desktop installation or navigate to MATLAB Online. Ensure your current working directory contains your target data files.
-
Deduplicate a 1D numerical vector with default ascending sorting:
By default,
uniqueextracts unique elements and sorts them in ascending numerical order:% Step 2: Basic 1D vector deduplication raw_measurements = [42, 17, 85, 17, 42, 99, 17]; C = unique(raw_measurements); % Output: % C = [17, 42, 85, 99] -
Preserve original sequence order using the ‘stable’ option:
In time-series analysis or sequential sensor logging, sorting values alters the temporal chronology. Use the
'stable'flag to maintain the original order of appearance:% Step 3: Sequence-preserving deduplication C_stable = unique(raw_measurements, 'stable'); % Output: % C_stable = [42, 17, 85, 99] -
Extract index vectors for data mapping and reconstruction:
Call
uniquewith three output arguments to obtain the unique arrayC, the index vectoria(positions in the original array), and the index vectoric(reconstruction mapping):% Step 4: Extract index vectors [C, ia, ic] = unique(raw_measurements); % Output: % C = [17, 42, 85, 99] % ia = [2; 1; 3; 6] -- raw_measurements(ia) equals C % ic = [2; 1; 3; 1; 2; 4; 1] -- C(ic) reconstructs raw_measurements -
Extract unique rows from a multi-column observation matrix:
To treat each row of a 2D matrix or table as a distinct observational unit, supply the
'rows'argument:% Step 5: Multi-column row deduplication trial_matrix = [ 101, 1, 24.5; 102, 1, 31.0; 101, 1, 24.5; % Exact duplicate row 103, 2, 19.8; 102, 1, 31.0 % Exact duplicate row ]; [unique_trials, ia_rows, ic_rows] = unique(trial_matrix, 'rows'); % unique_trials returns a 3x3 matrix of distinct observation rows: % [101, 1, 24.5; % 102, 1, 31.0; % 103, 2, 19.8] -
Compute categorical frequency counts without loops:
Leverage the reconstruction index
icwithaccumarrayto determine how many times each distinct value occurs:% Step 6: Vectorized frequency computation counts = accumarray(ic(:), 1); frequency_table = table(C(:), counts, 'VariableNames', ["UniqueValue", "Frequency"]); disp(frequency_table);
Output and how to read it
Calling [C, ia, ic] = unique(...) yields three interrelated output arrays that serve distinct analytical functions in scientific programming:
| Output Argument | Data Type / Dimensions | Mathematical Relationship | Practical Research Interpretation |
|---|---|---|---|
| C | Same type as input A |
Distinct elements or rows | The deduplicated set. Represents the complete vocabulary of unique observations or levels in the dataset. |
| ia | Column vector of positive integers | C = A(ia) or C = A(ia,:) |
Index vector of appearance. Identifies where each unique element first appeared (or last appeared if 'last' was specified). Enables downsampling aligned metadata arrays (such as timestamps or subject notes) to match the deduplicated set. |
| ic | Column vector of positive integers | A = C(ic) or A(:) = C(ic) |
Index vector of reconstruction. Maps every element of the original array to its corresponding position in C. Serves as a 1-based integer factor encoding suitable for grouping, aggregation, and contingency tables. |
For example, if an experimental sensor vector is defined as A = [50, 10, 50, 20], [C, ia, ic] = unique(A) produces:
C = [10, 20, 50]: Sorted unique values.ia = [2; 4; 1]: 10 was first found at index 2, 20 at index 4, and 50 at index 1. EvaluatingA(ia)returns[10, 20, 50].ic = [3; 1; 3; 2]: Element 1 ofA(50) isC(3); element 2 (10) isC(1); element 3 (50) isC(3); element 4 (20) isC(2). EvaluatingC(ic)perfectly reconstructsA.
Troubleshooting
When running array deduplication on complex empirical data, researchers frequently encounter specific edge cases. Consult these verified diagnostic resolutions:
1. Seemingly identical floating-point numbers do not deduplicate
Cause: MATLAB’s standard unique function enforces strict binary equality (==). In numerical simulations or iterative calculations, round-off errors at machine precision (e.g., 1e-16) cause values that appear identical on the display to differ internally.
Resolution: Use the official uniquetol function (introduced in MATLAB R2015a) to specify a relative or absolute numerical tolerance:
% Group floating-point numbers within a relative tolerance of 1e-6
x = [1.00000000, 1.00000005, 2.50000000];
C_tol = uniquetol(x, 1e-6);
% C_tol collapses the first two values into a single cluster: [1.0, 2.5]
2. The ‘rows’ option throws an error on 3D or N-D arrays
Cause: The 'rows' argument is mathematically defined only for 2D matrices, tables, and timetables. Passing higher-dimensional tensors generates an error indicating unsupported dimensionality.
Resolution: Reshape the N-D array into a 2D matrix before calling unique, or iterate along specific slice dimensions depending on your tensor architecture.
3. Unexpected reordering of sequential or chronological observations
Cause: The default ordering mode is 'sorted', which reorders values in ascending order and disrupts event chronologies.
Resolution: Always pass the 'stable' flag: C = unique(A, 'stable') or C = unique(A, 'rows', 'stable') when chronological or appearance ordering must remain intact.
4. Discrepancies in NaN (missing value) handling
Cause: In legacy MATLAB releases (or code using "legacy" mode), NaN values were treated as distinct entities because IEEE standard comparisons state NaN ~= NaN. In modern MATLAB, all NaN, <undefined>, and NaT entries are treated as equivalent by default and clustered into a single missing value placed at the end of C.
Resolution: In MATLAB R2022b and later, use the TreatMissingAsDistinct name-value argument to explicitly govern missing value clustering:
% Preserve distinct missing value positions
data_with_nans = [10, NaN, 20, NaN, 10];
C_distinct_nan = unique(data_with_nans, TreatMissingAsDistinct=true);
5. Locating conditional positions rather than set uniqueness
Cause: Researchers often confuse deduplicating an array with finding the index positions of elements meeting specific boolean conditions.
Resolution: For locating indices matching logical expressions, use the find command in MATLAB rather than unique.
Free alternatives
Researchers transitioning code across computational environments or building open-source analytical pipelines can replicate MATLAB’s unique functionality using these free, verified tools:
| Software / Environment | Basic Unique Syntax | Row Deduplication Syntax | Index Mapping Support | Official Reference Documentation |
|---|---|---|---|---|
| GNU Octave | y = unique(x) |
y = unique(x, "rows") |
Direct drop-in parity: [y, ia, ic] = unique(x) |
GNU Octave Documentation (Set Operations: unique and uniquetol) |
| Python (NumPy) | numpy.unique(ar) |
numpy.unique(ar, axis=0) |
return_index=True (ia) and return_inverse=True (ic) |
NumPy API Reference (numpy.unique) |
| R (Base R) | unique(x) |
unique(df) or unique(mat) |
Constructed via match(x, unique(x)) |
R Base Package Documentation (base::unique) |
| Julia (Base) | unique(A) |
unique(A, dims=1) |
Constructed via indexin(A, unique(A)) |
Julia Base Language Reference (Base.unique) |
GNU Octave provides near 100% syntax and behavioral compatibility with MATLAB scripts, making it the most direct open-source drop-in replacement. Researchers evaluating broader analytical tradeoffs across scripting platforms can explore our comparative analysis on MATLAB vs R.
FAQ
What does unique do in MATLAB?
The unique function in MATLAB removes duplicate elements from vectors, arrays, strings, cell arrays, or tables. By default, it returns the distinct values in ascending sorted order. With additional arguments, it can preserve original element order ('stable'), deduplicate entire matrix rows ('rows'), and provide positional index vectors (ia and ic).
How do I keep the original order when using MATLAB unique?
Pass the 'stable' flag as the second argument: C = unique(A, 'stable'). This prevents MATLAB from sorting the values in ascending order, ensuring that unique values appear in C in the exact order they first occurred in A.
What do the ia and ic outputs mean in MATLAB unique?
When calling [C, ia, ic] = unique(A), ia contains the indices in A corresponding to each unique element in C (satisfying C = A(ia)). The ic vector contains the indices in C needed to reconstruct the original array A (satisfying A = C(ic)). Researchers use ic as a categorical grouping factor and ia to downsample parallel metadata vectors.
How do I find unique rows across multiple matrix columns in MATLAB?
Specify the 'rows' argument: [unique_rows, ia, ic] = unique(A, 'rows'). MATLAB treats each entire row of the 2D matrix or table as a unified record and returns distinct rows sorted lexicographically from left to right across columns.
How does MATLAB unique handle NaN and missing values?
In modern MATLAB releases, all missing values—including NaN, <undefined>, and NaT (Not-a-Time)—are treated as mutually equal duplicates and grouped into a single missing entry positioned at the end of the unique output array. In MATLAB R2022b and later, setting TreatMissingAsDistinct=true treats each missing entry as a distinct value.
How do I count the occurrences of each unique value in MATLAB?
You can count occurrences without writing a loop by passing the reconstruction vector ic to accumarray: counts = accumarray(ic(:), 1). Alternatively, in newer MATLAB releases, the groupcounts function can be called directly on the array or table.
Sources
- MathWorks Documentation. unique: Unique values in array. Natick, MA: The MathWorks, Inc. https://www.mathworks.com/help/matlab/ref/unique.html (read 2026-11-09).
- MathWorks Documentation. uniquetol: Unique values within tolerance. Natick, MA: The MathWorks, Inc. https://www.mathworks.com/help/matlab/ref/uniquetol.html (read 2026-11-09).
- GNU Octave Documentation. Set Operations: unique and uniquetol. Free Software Foundation. https://docs.octave.org/latest/Sets.html (read 2026-11-09).
- NumPy Developers. numpy.unique API Reference. NumPy Project. https://numpy.org/doc/stable/reference/generated/numpy.unique.html (read 2026-11-09).







