sort — Sort array elements along a dimension with MATLAB-compatible direction options and optional index outputs.
sort orders elements along a selected dimension, defaulting to ascending order on the first non-singleton dimension. It also supports MATLAB-compatible index outputs that return permutation positions.
Syntax
B = sort(A)
B = sort(A, arg1)
B = sort(A, arg1, arg2)
B = sort(A, ..., "ComparisonMethod", method)
B = sort(A, ..., "MissingPlacement", placement)
[B, I] = sort(A)All supported sort forms
B = sort(A)
B = sort(A, arg1)
B = sort(A, arg1, arg2)
B = sort(A, ..., "ComparisonMethod", method)
B = sort(A, ..., "MissingPlacement", placement)
[B, I] = sort(A)
[B, I] = sort(A, arg1)
[B, I] = sort(A, arg1, arg2)
[B, I] = sort(A, ..., "ComparisonMethod", method)
[B, I] = sort(A, ..., "MissingPlacement", placement)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
A | Any | Yes | — | Input array. |
arg1 | Any | Yes | — | Dimension selector or direction token ('ascend'/'descend'). |
arg1 | Any | Yes | — | Dimension selector, placeholder, or direction token. |
arg2 | Any | Yes | — | Dimension selector or direction token. |
arg | Any | Variadic | — | Optional dimension/direction arguments. |
name | StringScalar | Yes | "ComparisonMethod" | Name-value option key. |
method | StringScalar | Yes | "auto" | Comparison method: 'auto', 'real', or 'abs'. |
name | StringScalar | Yes | "MissingPlacement" | Name-value option key. |
placement | StringScalar | Yes | "auto" | Requested NaN placement option (currently unsupported). |
Returns
| Name | Type | Description |
|---|---|---|
B | Any | Sorted values. |
I | NumericArray | One-based index permutation for each sorted slice. |
Returned values from sort depend on how many outputs the caller requests.
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:sort:InvalidDimension | Dimension argument is non-positive, non-integer, or otherwise invalid. | sort: invalid dimension argument |
RunMat:sort:ComparisonMethodRequiresString | ComparisonMethod option value is not string-like. | sort: 'ComparisonMethod' requires a string value |
RunMat:sort:ComparisonMethodUnknown | ComparisonMethod option value is not one of 'auto'/'real'/'abs'. | sort: unsupported ComparisonMethod |
RunMat:sort:MissingPlacementUnsupported | MissingPlacement option is provided but unsupported. | sort: the 'MissingPlacement' option is not supported yet |
RunMat:sort:InvalidArgument | Parser encounters invalid or unrecognized option/value arguments. | sort: invalid argument sequence |
RunMat:sort:Internal | Internal conversion, allocation, or provider result construction fails. | sort: internal operation failed |
How sort works
- Scalars remain unchanged; vectors are reordered into ascending or descending order.
- For matrices and higher-dimensional tensors, the sort operates along a specified dimension (default: first non-singleton). All other dimensions remain untouched.
[B, I] = sort(A, ...)returns both the sorted valuesBand the permutation indicesI, using MATLAB's one-based indexing.- Direction arguments accept
'ascend'(default) or'descend'. - Name-value pairs support
'ComparisonMethod'with values'auto','real', or'abs'. The'abs'option sorts by absolute value while breaking ties using the signed value. - For complex inputs, the default
'ComparisonMethod'='auto'behaves like'abs'(magnitude ordering) and'real'compares the real component first with the imaginary component used for tie-breaking. - NaN values are treated as missing: they appear at the end for ascending sorts and at the beginning for descending sorts (matching MATLAB's
'MissingPlacement','auto'behaviour for doubles). - Dimensions greater than
ndims(A)are treated as singleton dimensions (size 1) and therefore leaveAunchanged while returning index values of1.
Does RunMat run sort on the GPU?
sort is registered as a sink builtin. When tensors reside on a GPU without a specialised sort kernel, RunMat gathers them to host memory, performs the sort, and returns host-resident outputs.
Providers may implement a future sort_dim hook to keep data on the GPU. Until then, all providers fall back to the host path automatically.
The returned index tensor is always host-resident double precision.
Examples
Sorting a column vector in ascending order
A = [3; 1; 2];
B = sort(A)Expected output:
B =
1
2
3Sorting rows by specifying the dimension
A = [1 4 2; 3 2 5];
B = sort(A, 2)Expected output:
B =
1 2 4
2 3 5Sorting values in descending order
A = [10 4 7 9];
B = sort(A, 'descend')Expected output:
B =
10 9 7 4Retrieving permutation indices alongside the sorted values
A = [4 1 9 2];
[B, I] = sort(A)Expected output:
B =
1 2 4 9
I =
2 4 1 3Sorting by absolute value using ComparisonMethod
A = [-8 -1 3 -2];
B = sort(A, 'ComparisonMethod', 'abs')Expected output:
B =
-1 -2 3 -8Sorting tensors containing NaN values
A = [NaN 4 1 2];
[B, I] = sort(A)Expected output:
B =
1 2 4 NaN
I =
3 4 2 1Sorting GPU tensors with automatic host fallback
G = gpuArray(randn(5, 1));
[B, I] = sort(G, 'descend')Using sort with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how sort changes the result.
Run a small sort example, explain the result, then change one input and compare the output.
FAQ
Can sort return both values and indices?⌄
Yes. Use [B, I] = sort(A, ...) to receive the permutation indices alongside the sorted values.
How are NaN values handled?⌄
NaN values are considered missing. They appear last for ascending sorts and first for descending sorts, matching MATLAB's 'MissingPlacement','auto' default for doubles.
What happens when I sort along a dimension that does not exist?⌄
sort(A, dim) treats dimensions beyond ndims(A) as singleton dimensions (size 1). The data remains unchanged and the index output is filled with ones.
Does sort support name-value arguments?⌄
Yes. 'ComparisonMethod' accepts 'auto', 'real', or 'abs'. Other name-value pairs such as 'MissingPlacement' are currently not supported and raise an error.
Are GPU tensors sorted in-place?⌄
Not yet. sort is a sink builtin that gathers GPU tensors to host memory when no GPU sort kernel is available. Providers can implement specialised hooks in the future.
Does sort preserve the shape of the input?⌄
Yes. The output is the same size as the input tensor. Only values along the selected dimension are reordered.
What numeric type do the index outputs use?⌄
Permutation indices are returned as double-precision tensors (or scalars) using MATLAB's one-based indexing.
Is the sorting stable?⌄
Yes. Equal elements (including ties when sorting by absolute value) preserve their original order.
How does ComparisonMethod behave with real inputs?⌄
'auto' and 'real' behave identically. 'abs' sorts by absolute value and uses the signed value to break ties so that results match MATLAB.
How does ComparisonMethod behave with complex inputs?⌄
'auto' (the default) and 'abs' order values by magnitude. 'real' compares the real component first and falls back to the imaginary component to break ties while preserving stability.
Do logical or scalar inputs work?⌄
Yes. Logical inputs are promoted to double precision automatically. Scalars are returned unchanged with an index output of 1 when requested.
Related Array functions
Shape
cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · squeeze · tril · triu · vertcat
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how sort is executed, line by line, in Rust.
- View the source for sort in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 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.