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

sortrows — Sort matrix rows lexicographically with MATLAB-compatible column selection and direction controls.

sortrows reorders rows of matrices or character arrays in lexicographic order. It supports MATLAB-compatible controls for comparison columns and per-column ascending/descending direction.

Syntax

B = sortrows(A)
B = sortrows(A, column)
B = sortrows(A, direction)
B = sortrows(A, column, direction)
B = sortrows(A, ..., "ComparisonMethod", method)
B = sortrows(A, ..., "MissingPlacement", placement)
All supported sortrows forms
B = sortrows(A)
B = sortrows(A, column)
B = sortrows(A, direction)
B = sortrows(A, column, direction)
B = sortrows(A, ..., "ComparisonMethod", method)
B = sortrows(A, ..., "MissingPlacement", placement)
[B, I] = sortrows(A)
[B, I] = sortrows(A, column)
[B, I] = sortrows(A, direction)
[B, I] = sortrows(A, column, direction)
[B, I] = sortrows(A, ..., "ComparisonMethod", method)
[B, I] = sortrows(A, ..., "MissingPlacement", placement)

Inputs

A
Type
Any
Required
Yes
Description
Input matrix to sort by rows.
column
Type
NumericArray
Required
Yes
Description
Column specification vector (negative entries request descending order).
direction
Type
StringScalar
Required
Yes
Default
"ascend"
Description
Global row direction override: 'ascend' or 'descend'.
arg
Type
Any
Required
Variadic
Description
Optional column and 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
NaN placement policy: 'auto', 'first', or 'last'.
NameTypeRequiredDefaultDescription
AAnyYes—Input matrix to sort by rows.
columnNumericArrayYes—Column specification vector (negative entries request descending order).
directionStringScalarYes"ascend"Global row direction override: 'ascend' or 'descend'.
argAnyVariadic—Optional column and direction arguments.
nameStringScalarYes"ComparisonMethod"Name-value option key.
methodStringScalarYes"auto"Comparison method: 'auto', 'real', or 'abs'.
nameStringScalarYes"MissingPlacement"Name-value option key.
placementStringScalarYes"auto"NaN placement policy: 'auto', 'first', or 'last'.

Returns

B
Type
Any
Description
Sorted input rows.
I
Type
NumericArray
Description
Permutation indices mapping sorted rows to original rows.
NameTypeDescription
BAnySorted input rows.
INumericArrayPermutation indices mapping sorted rows to original rows.

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

Errors

RunMat:sortrows:InvalidColumnIndex
When
Column specification indices are out of range, zero, or otherwise invalid.
Message
sortrows: invalid column index
RunMat:sortrows:MissingPlacementUnknown
When
MissingPlacement option value is unsupported.
Message
sortrows: unsupported MissingPlacement value
RunMat:sortrows:InvalidArgument
When
Option parsing receives invalid argument kinds or malformed name-value pairs.
Message
sortrows: invalid argument
IdentifierWhenMessage
RunMat:sortrows:InvalidColumnIndexColumn specification indices are out of range, zero, or otherwise invalid.sortrows: invalid column index
RunMat:sortrows:MissingPlacementUnknownMissingPlacement option value is unsupported.sortrows: unsupported MissingPlacement value
RunMat:sortrows:InvalidArgumentOption parsing receives invalid argument kinds or malformed name-value pairs.sortrows: invalid argument
RunMat:sortrows:ComparisonMethodUnknownComparisonMethod option value is unsupported.sortrows: unsupported ComparisonMethod value
RunMat:sortrows:UnsupportedInputTypeInput cannot be converted to numeric, logical, complex, or char matrix domain.sortrows: unsupported input type
RunMat:sortrows:MatrixRequiredInput has rank greater than 2 where matrix input is required.sortrows: input must be a 2-D matrix
RunMat:sortrows:InternalInternal conversion/allocation/provider decode fails.sortrows: internal operation failed

Behavior

sortrows(A) sorts by column 1, then column 2, and so on, all in ascending order.

sortrows(A, C) treats the vector C as the column order. Positive entries sort ascending; negative entries sort descending.

sortrows(A, 'descend') sorts all columns in descending order. Combine this with a column vector to mix directions.

[B, I] = sortrows(A, ...) also returns I, the 1-based row permutation indices.

sortrows is stable: rows that compare equal keep their original order.

For complex inputs, 'ComparisonMethod' accepts 'auto', 'real', or 'abs', using the supported comparison rules.

NaN handling mirrors MATLAB: in ascending sorts rows containing NaN values move to the end; in descending sorts they move to the beginning.

'MissingPlacement' lets you choose whether NaN (and other missing) rows appear 'first', 'last', or follow MATLAB's 'auto' default.

Character arrays are sorted lexicographically using their character codes.

Types, placement and limitations

Matrix and character rows, and table rows with variable selectors, are supported. String arrays are not supported. Matrix values retain their class and shape; row indices are double columns. Resident outputs are restored to the input owner after provider or host evaluation. Missing placement is applied lexicographically at each selected key, not as a separate whole-row bucket.

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.

Syntax

example: {"description":"Syntax","input":"B = sortrows(A)\nB = sortrows(A, column)\nB = sortrows(A, column, direction)\n[B, index] = sortrows(___)"}

points: ["A is the data to sort — typically a numeric or character matrix. Tables and timetables are also accepted by MATLAB's sortrows API (RunMat currently supports matrix and char-array inputs fully).","column selects the sort keys. It can be a single column index or a vector of indices; negative entries sort that column in descending order (for example, [1 -3] sorts ascending by column 1 then descending by column 3).","direction is an optional 'ascend' or 'descend' string, or a cell array of strings matching column entry-for-entry. It can be combined with signed column vectors to override per-column directions.","index is the optional second output: a row-permutation vector such that B = A(index, :). Use it to reorder paired arrays or to undo the sort."]

Examples

Sorting rows of a matrix in ascending order

A = [3 2; 1 4; 2 1];
B = sortrows(A)

Expected output:

B =
     1     4
     2     1
     3     2

Sorting by a custom column order

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

Expected output:

B =
     3     2     1
     3     2     5
     1     4     2

Sorting rows in descending order

A = [2 8; 4 1; 3 5];
B = sortrows(A, 'descend')

Expected output:

B =
     4     1
     3     5
     2     8

Mixing ascending and descending directions

A = [1 7 3; 1 2 9; 1 2 3];
B = sortrows(A, [1 -2 3])

Expected output:

B =
     1     7     3
     1     2     3
     1     2     9

Sorting rows of a character array

names = ['bob '; 'al  '; 'ally'];
sorted = sortrows(names)

Expected output:

sorted =
al
ally
bob

Sorting rows of complex data by magnitude

Z = [3+4i, 3; 1+2i, 4];
B = sortrows(Z, 'ComparisonMethod', 'abs')

Expected output:

B =
    1.0000 + 2.0000i    4.0000
    3.0000 + 4.0000i    3.0000

Forcing NaN rows to the top

A = [1 NaN; NaN 2];
B = sortrows(A, 'MissingPlacement', 'first')

Expected output:

B =
   NaN     2
     1   NaN

Sorting GPU-resident data with automatic host fallback

G = gpuArray([3 1; 2 4; 1 2]);
[B, I] = sortrows(G)

Using sortrows with coding agents

Open a RunMat example with live inputs, then ask the agent to explain how sortrows changes the result.

Run a small sortrows example, explain the result, then change one input and compare the output.

FAQ

Can I request the permutation indices?⌄

Yes. Call [B, I] = sortrows(A, ...) to receive the 1-based row permutation indices in I.

How do I sort specific columns?⌄

Provide a column vector, e.g. sortrows(A, [2 -3]) sorts by column 2 ascending and column 3 descending.

What happens when rows contain NaN values?⌄

Rows containing NaNs move to the bottom for ascending sorts and to the top for descending sorts when 'MissingPlacement' is left at its 'auto' default, matching MATLAB.

How can I force NaNs or missing values to the top or bottom?⌄

Use the name-value pair 'MissingPlacement','first' to place missing rows before finite ones, or 'MissingPlacement','last' to move them to the end regardless of direction.

Does sortrows work with complex numbers?⌄

Yes. Use 'ComparisonMethod','real' to sort by the real component or 'abs' to sort by magnitude (the default behaviour matches MATLAB's 'auto' rules).

Can I combine a direction string with a column vector?⌄

Yes. sortrows(A, [1 3], 'descend') applies descending order to both columns after applying the specified column order.

Is the operation stable?⌄

Yes. Rows that compare equal remain in their original order.

Does sortrows mutate its input?⌄

No. It returns a sorted copy of the input. GPU inputs are gathered to host memory when required.

Are string arrays supported?⌄

String arrays are not yet supported. Convert them to character matrices or use tables before sorting.

What does sortrows do in MATLAB?⌄

sortrows(A) sorts the rows of matrix A in ascending order based on the elements in the first column. Rows with equal first-column values are sorted by subsequent columns.

How do I sort by a specific column in MATLAB?⌄

Use sortrows(A, col) where col is the column index. Use negative values for descending order, e.g., sortrows(A, -2) sorts by the second column in descending order.

Is sortrows a stable sort?⌄

Yes. sortrows uses a stable sorting algorithm, meaning rows with equal sort keys retain their original relative order.

Is there a sortrows equivalent in NumPy or pandas?⌄

— In pandas use df.sort_values(by=['col1', 'col2'], ascending=[True, False]). In NumPy there is no direct sortrows, but A[np.lexsort(A.T[::-1])] sorts rows lexicographically (NumPy's lexsort reads its keys in reverse priority, so the [::-1] restores MATLAB's left-to-right order). For descending columns, negate the corresponding key: np.lexsort([-A[:, 1], A[:, 0]]).

How do I sort by multiple columns with different directions?⌄

— Pass a signed column vector as the second argument. Positive entries sort ascending, negative entries sort descending. For example, sortrows(A, [1 -2]) sorts column 1 ascending and column 2 descending, and sortrows(A, [3 -1 2]) orders by column 3 ascending, column 1 descending, then column 2 ascending as a tiebreaker. You can also write sortrows(A, [1 2], {'ascend','descend'}) for the equivalent name-based form.

Related Array functions

Sorting Sets

argsort · intersect · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sort · 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 sortrows is executed, line by line, in Rust.

  • View the source for sortrows 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
  • Syntax
  • Examples
  • Sorting rows of a matrix in ascending order
  • Sorting by a custom column order
  • Sorting rows in descending order
  • Mixing ascending and descending directions
  • Sorting rows of a character array
  • Sorting rows of complex data by magnitude
  • Forcing NaN rows to the top
  • Sorting GPU-resident data with automatic host fallback
  • Using sortrows with coding agents
  • FAQ
  • Related Array functions
  • Sorting Sets
  • Accumulation
  • Shape
  • Creation
  • Combinatorics
  • Binning
  • Indexing
  • Grouping
  • Introspection
  • Source you can read
  • About RunMat