argsort — Return permutation indices that sort arrays along a dimension in MATLAB and RunMat.
argsort(X) returns the permutation indices that order X the same way sort(X) would. It matches [~, I] = sort(X, ...) index behavior for dimension and direction options in MATLAB and RunMat.
Syntax
I = argsort(A)
I = argsort(A, arg1)
I = argsort(A, arg1, arg2)
I = argsort(A, ..., "ComparisonMethod", method)
I = argsort(A, ..., "MissingPlacement", placement)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
A | Any | Yes | — | Input array. |
arg1 | Any | Yes | — | Dimension selector or direction token. |
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 |
|---|---|---|
I | NumericArray | One-based permutation indices that sort each slice. |
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 |
How argsort works
- Operates along the first non-singleton dimension by default. Pass a dimension argument to override.
- Accepts the same direction keywords as
sort:'ascend'(default) or'descend'. - Supports
'ComparisonMethod'values'auto','real', and'abs'for real and complex inputs. - Returns indices as double-precision tensors using MATLAB's one-based indexing.
- Treats NaN values as missing: they appear at the end for ascending permutations and at the beginning for descending permutations.
- Acts as a residency sink. GPU tensors are gathered when the active provider does not expose a specialised sort kernel.
Does RunMat run argsort on the GPU?
argsort shares the sort_dim provider hook with the sort builtin. When implemented, indices are computed without leaving the device.
If the provider lacks sort_dim, RunMat gathers tensors to host memory, evaluates the permutation, and returns host-resident indices.
Outputs are always host-resident double tensors because permutation indices are consumed immediately by host-side logic (e.g., indexing).
Examples
Getting indices that sort a vector
A = [4; 1; 3];
idx = argsort(A)Expected output:
idx =
2
3
1Reordering data with the permutation indices
A = [3 9 1 5];
idx = argsort(A);
sorted = A(idx)Expected output:
sorted =
1 3 5 9Sorting along a specific dimension
A = [1 6 4; 2 3 5];
idx = argsort(A, 2)Expected output:
idx =
1 3 2
1 2 3Descending order permutations
A = [10 4 7 9];
idx = argsort(A, 'descend')Expected output:
idx =
1 4 3 2Using ComparisonMethod to sort by magnitude
A = [-8 -1 3 -2];
idx = argsort(A, 'ComparisonMethod', 'abs')Expected output:
idx =
2 4 3 1Handling NaN values during permutation
A = [NaN 4 1 2];
idx = argsort(A)Expected output:
idx =
3 4 2 1Argsort on GPU tensors falls back gracefully
G = gpuArray(randn(5, 1));
idx = argsort(G)Using argsort with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how argsort changes the result.
Run a small argsort example, explain the result, then change one input and compare the output.
FAQ
How is argsort different from sort?⌄
argsort returns only the permutation indices. It behaves like calling [~, I] = sort(X, ...) without materialising the sorted values.
Are the indices one-based like MATLAB?⌄
Yes. All indices follow MATLAB's one-based convention so they can be used directly with subsequent indexing operations.
Does argsort support the same arguments as sort?⌄
Yes. Dimension arguments, direction keywords, and 'ComparisonMethod' behave exactly like they do for sort.
How are NaN values ordered?⌄
NaNs are treated as missing. They appear at the end for ascending permutations and at the beginning for descending permutations, matching MATLAB.
Can I call argsort on GPU arrays?⌄
Yes. When the active provider implements the sort_dim hook, permutations stay on the device. Otherwise tensors are gathered automatically and sorted on the host.
Is the permutation stable?⌄
Yes. Equal elements keep their relative order so that argsort remains consistent with MATLAB's stable sorting semantics.
What type is returned?⌄
A double-precision tensor (or scalar) with the same shape as the input, containing permutation indices.
Does argsort mutate its input?⌄
No. It only returns indices. Combine the result with indexing (A(idx)) to obtain reordered values when needed.
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 argsort is executed, line by line, in Rust.
- View the source for argsort 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.