RunMat
  • Pricing
RunMat
GitHub
GitHub
Sign inTry in browser
DesktopRuntimePhysicsCADAdministrationAgent

Get RunMat updates

New releases, guides and examples.

Product+
  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download
Math+
  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting
Physics+
  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA
Industries+
  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance
Learn+
  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students
Compare+
  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons
Company+
  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms

Product

  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download

Math

  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting

Physics

  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA

Industries

  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance

Learn

  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students

Compare

  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons

Company

  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms
GitHubXLinkedIn

© Dystr, Inc. · RunMat v0.7.1, Nov 17, 2026

RunMat® is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

/
See all docs
Builtin Reference
    • argsort
    • intersect
    • ismember
    • ismembertol
    • issorted
    • issortedrows
    • setdiff
    • setxor
    • sort
    • sortrows
    • union
    • unique

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

A
Type
Any
Required
Yes
Description
Input array.
arg1
Type
Any
Required
Yes
Description
Dimension selector or direction token ('ascend'/'descend').
arg1
Type
Any
Required
Yes
Description
Dimension selector, placeholder, or direction token.
arg2
Type
Any
Required
Yes
Description
Dimension selector or direction token.
arg
Type
Any
Required
Variadic
Description
Optional dimension/direction arguments.
name
Type
StringScalar
Required
Yes
Default
"ComparisonMethod"
Description
Name-value option key.
method
Type
StringScalar
Required
Yes
Default
"auto"
Description
Comparison method: 'auto', 'real', or 'abs'.
name
Type
StringScalar
Required
Yes
Default
"MissingPlacement"
Description
Name-value option key.
placement
Type
StringScalar
Required
Yes
Default
"auto"
Description
Missing-value placement: 'auto', 'first', or 'last'.
NameTypeRequiredDefaultDescription
AAnyYes—Input array.
arg1AnyYes—Dimension selector or direction token ('ascend'/'descend').
arg1AnyYes—Dimension selector, placeholder, or direction token.
arg2AnyYes—Dimension selector or direction token.
argAnyVariadic—Optional dimension/direction arguments.
nameStringScalarYes"ComparisonMethod"Name-value option key.
methodStringScalarYes"auto"Comparison method: 'auto', 'real', or 'abs'.
nameStringScalarYes"MissingPlacement"Name-value option key.
placementStringScalarYes"auto"Missing-value placement: 'auto', 'first', or 'last'.

Returns

B
Type
Any
Description
Sorted values.
I
Type
NumericArray
Description
One-based index permutation for each sorted slice.
NameTypeDescription
BAnySorted values.
INumericArrayOne-based index permutation for each sorted slice.

Returned values from sort depend on how many outputs the caller requests.

Errors

RunMat:sort:InvalidDimension
When
Dimension argument is non-positive, non-integer, or otherwise invalid.
Message
sort: invalid dimension argument
RunMat:sort:ComparisonMethodRequiresString
When
ComparisonMethod option value is not string-like.
Message
sort: 'ComparisonMethod' requires a string value
RunMat:sort:ComparisonMethodUnknown
When
ComparisonMethod option value is not one of 'auto'/'real'/'abs'.
Message
sort: unsupported ComparisonMethod
IdentifierWhenMessage
RunMat:sort:InvalidDimensionDimension argument is non-positive, non-integer, or otherwise invalid.sort: invalid dimension argument
RunMat:sort:ComparisonMethodRequiresStringComparisonMethod option value is not string-like.sort: 'ComparisonMethod' requires a string value
RunMat:sort:ComparisonMethodUnknownComparisonMethod option value is not one of 'auto'/'real'/'abs'.sort: unsupported ComparisonMethod
RunMat:sort:MissingPlacementRequiresStringMissingPlacement option value is not string-like.sort: 'MissingPlacement' requires a string value
RunMat:sort:MissingPlacementUnknownMissingPlacement option value is not one of 'auto'/'first'/'last'.sort: unsupported MissingPlacement
RunMat:sort:InvalidArgumentParser encounters invalid or unrecognized option/value arguments.sort: invalid argument sequence
RunMat:sort:InternalInternal conversion, allocation, or provider result construction fails.sort: internal operation failed

Behavior

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 values B and the permutation indices I, 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 leave A unchanged while returning index values of 1.

Types, placement and limitations

Sorting is not in-place. It preserves the input shape and native numeric or logical class; indices are doubles of the same shape. Resident values and indices are restored to the input owner. Eligible same-class real inputs may use a provider hook; unsupported candidates are gathered exactly before host evaluation.

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

Sorting a column vector in ascending order

A = [3; 1; 2];
B = sort(A)

Expected output:

B =
     1
     2
     3

Sorting rows by specifying the dimension

A = [1 4 2; 3 2 5];
B = sort(A, 2)

Expected output:

B =
     1     2     4
     2     3     5

Sorting values in descending order

A = [10 4 7 9];
B = sort(A, 'descend')

Expected output:

B =
    10     9     7     4

Retrieving 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     3

Sorting by absolute value using ComparisonMethod

A = [-8 -1 3 -2];
B = sort(A, 'ComparisonMethod', 'abs')

Expected output:

B =
    -1    -2     3    -8

Sorting tensors containing NaN values

A = [NaN 4 1 2];
[B, I] = sort(A)

Expected output:

B =
     1     2     4   NaN
I =
     3     4     2     1

Sorting 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'. 'MissingPlacement' accepts 'auto', 'first', or 'last'.

Are GPU tensors sorted in-place?⌄

Sorting is not in-place. It preserves the input shape and native numeric or logical class; indices are doubles of the same shape. Resident values and indices are restored to the input owner. Eligible same-class real inputs may use a provider hook; unsupported candidates are gathered exactly before host evaluation. 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 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 comparison keys preserve their original order. For real absolute-value comparison, signed value breaks equal-magnitude ties.

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 sort inputs retain their logical class. Scalars are returned unchanged with an index output of 1 when requested.

Related Array functions

Sorting Sets

argsort · intersect · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sortrows · union · unique

Accumulation

accumarray

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

combinations · nchoosek · perms

Binning

discretize

Indexing

find · ind2sub · sub2ind

Grouping

findgroups · groupcounts · grp2idx · splitapply

Introspection

height · iscolumn · isempty · ismatrix · isrow · isscalar · isvector · length · ndims · numel · size · width

Source you can read

Every RunMat function's source is public. 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 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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • Behavior
  • Types, placement and limitations
  • Resident execution
  • Examples
  • Sorting a column vector in ascending order
  • Sorting rows by specifying the dimension
  • Sorting values in descending order
  • Retrieving permutation indices alongside the sorted values
  • Sorting by absolute value using ComparisonMethod
  • Sorting tensors containing NaN values
  • Sorting GPU tensors with automatic host fallback
  • Using sort with coding agents
  • FAQ
  • Related Array functions
  • Sorting Sets
  • Accumulation
  • Shape
  • Creation
  • Combinatorics
  • Binning
  • Indexing
  • Grouping
  • Introspection
  • Source you can read
  • About RunMat