RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact

Explore

  • RunMat for academia
  • RunMat vs MATLAB Online
  • Benchmarks

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

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.

LicensePrivacy
/
See all docs
Builtin Reference
    • fieldnames
    • getfield
    • isfield
    • orderfields
    • rmfield
    • setfield
    • struct
    • structfun

orderfields — Reorder struct field definitions alphabetically or according to supplied ordering rules.

orderfields(S, ...) reorders struct-field definitions using alphabetical order, another struct's field order, explicit field-name lists, or permutation vectors, following MATLAB-compatible behavior.

Syntax

S = orderfields(S)
S = orderfields(S, order)
[S,P] = orderfields(S)
[S,P] = orderfields(S, order)

Inputs

NameTypeRequiredDefaultDescription
SAnyYes—Input struct or struct array.
orderAnyNo—Reference struct, field-name list, or permutation vector.

Returns

NameTypeDescription
SAnyStruct or struct array with reordered fields.
PNumericArrayPermutation vector mapping ordered fields to original positions.

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

Errors

IdentifierWhenMessage
orderfields:TooManyInputsMore than two input arguments are supplied.orderfields: expected at most two input arguments
orderfields:InvalidInputFirst argument is not a struct or struct array.orderfields: first argument must be a struct or struct array
orderfields:EmptyStructArrayEmpty struct array is asked to adopt a non-empty reference order.orderfields: empty struct arrays cannot adopt a non-empty reference order
orderfields:NoFieldsOrdering is requested for a struct array with no fields.orderfields: struct array has no fields to reorder
orderfields:InvalidStructArrayA struct-array element is not a struct.orderfields: struct array element is not a struct
orderfields:InvalidStructContentsStruct-array contents are not all structs.orderfields: expected struct array contents to be structs
orderfields:RebuildFailedRebuilding reordered struct array failed.orderfields: failed to rebuild struct array
orderfields:InvalidReferenceReference struct-array contains non-struct values.orderfields: reference struct array element is not a struct
orderfields:InvalidFieldNameListName-list entries are not scalar strings or character vectors.orderfields: cell array elements must be a string or character vector
orderfields:EmptyFieldNameRequested field-name list contains an empty name.orderfields: field names must be nonempty
orderfields:InvalidPermutationPermutation vector does not include each field exactly once.orderfields: index vector must permute every field exactly once
orderfields:IndexNotIntegerPermutation vector contains non-integer entries.orderfields: index vector must contain integers
orderfields:IndexOutOfRangePermutation vector index is outside valid field range.orderfields: index vector element out of range
orderfields:DuplicateIndexPermutation vector contains duplicate positions.orderfields: index vector contains duplicate positions
orderfields:FieldMismatchRequested field set does not exactly match struct fields.orderfields: field names must match the struct exactly
orderfields:UnknownFieldRequested order references an unknown field.orderfields: unknown field in requested order
orderfields:DuplicateFieldRequested field order includes duplicate names.orderfields: duplicate field in requested order
orderfields:MissingFieldA field from the requested order is missing on the struct.orderfields: field does not exist on the struct
orderfields:InvalidOrderArgumentSecond argument is not a supported order descriptor.orderfields: unrecognised ordering argument
orderfields:InternalErrorInternal permutation tensor construction failed.orderfields: internal error

How orderfields works

  • Works with scalar structs and struct arrays (RunMat stores struct arrays internally as cell arrays of structs).
  • The default behavior orderfields(S) sorts valid field names in documented ASCII order, with uppercase letters before lowercase letters.
  • orderfields(S, referenceStruct) matches the order of referenceStruct. Both structs must contain the same field names.
  • orderfields(S, {'b','a','c'}) or orderfields(S, string(['b','a','c'])) uses the supplied list of field names.
  • orderfields(S, [2 1 3]) reorders fields using a permutation vector that references the current field order.
  • Permutation scalars and vectors accept all eight integer classes and are validated exactly; a one-field structure therefore accepts an exact typed scalar 1.
  • [T, P] = orderfields(S, ___) returns the reordered struct (or struct array) T and a permutation vector P whose elements are the original 1-based field positions. Reuse P to apply the same order to other structs that share the field set.
  • Integer field contents retain exact class, shape, and value, and nested GPU handles retain residency/provenance; field reordering performs no payload gather or floating materialization.
  • Errors are raised when requested field names do not match the struct, when indices are invalid, or when the input is not a struct.

Does RunMat run orderfields on the GPU?

orderfields operates on host-side struct metadata only. When a struct contains GPU tensors or handles, the handles remain valid and resident on the device. No kernels are dispatched and no data is gathered or copied between host and device.

GPU memory and residency

No. Struct field reordering never moves or converts the values stored inside the struct. Existing GPU handles remain on the device. You can freely combine orderfields with gpuArray, gather, or auto-offload features without affecting residency.

Examples

How to sort struct fields alphabetically

s = struct("beta", 2, "alpha", 1, "gamma", 3);
t = orderfields(s);
fieldnames(t)

Expected output:

ans =
    {'alpha'}
    {'beta'}
    {'gamma'}

Match the field order of another struct

source = struct("y", 20, "x", 10);
template = struct("x", 0, "y", 0);
[aligned, order] = orderfields(source, template)

Reorder fields with a cell array of names

s = struct("a", 1, "b", 2, "c", 3);
u = orderfields(s, {"c", "a", "b"});
fieldnames(u)

Expected output:

ans =
    {'c'}
    {'a'}
    {'b'}

Reorder fields with an index vector

s = struct("first", 1, "second", 2, "third", 3);
permuted = orderfields(s, [3 1 2]);
fieldnames(permuted)

Expected output:

ans =
    {'third'}
    {'first'}
    {'second'}

Apply a custom order to every element of a struct array

records = struct("name", {"Ada", "Grace"}, "id", {101, 102});
[reordered, perm] = orderfields(records, {"id", "name"});
{reordered.id}

Expected output:

ans =
    {[101]}    {[102]}

Sort fields in descending alphabetical order

s = struct("alpha", 1, "delta", 4, "beta", 2);
names = string(fieldnames(s));
desc = orderfields(s, flip(names));
fieldnames(desc)

Expected output:

ans =
    {'delta'}
    {'beta'}
    {'alpha'}

Using orderfields with coding agents

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

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

FAQ

What argument forms does orderfields accept?⌄

You can pass a reference struct (scalar or struct array), a cell array or string array of field names, or a numeric permutation vector. Every variant must reference each existing field exactly once.

Does the reference struct have to contain the same fields?⌄

Yes. RunMat mirrors MATLAB and requires that the reference struct contain exactly the same field names. Missing or extra fields raise an error.

Can I reorder struct arrays?⌄

Yes. Every element in the struct array is reordered using the same field order. The array must contain structs only.

How are numeric vectors interpreted?⌄

Numeric vectors are treated as permutations of the current field order. Values must be positive integers that reference each existing field exactly once.

What happens when I pass duplicate field names?⌄

Duplicates are rejected with an error. Every field must appear exactly once in the requested order.

Does orderfields gather GPU data back to the CPU?⌄

No. The builtin only reorders metadata in the struct. GPU handles remain on the device and are not touched.

Can I reorder an empty struct array?⌄

Empty struct arrays are returned unchanged. Because RunMat stores field metadata per element, you must supply at least one element before an explicit order can be derived.

How do I maintain the existing order?⌄

Capture the permutation output once: [~, P] = orderfields(S);. You can later call orderfields(S, P) (or apply the same P to another struct with identical fields) to reapply the original order.

Does orderfields affect nested structs?⌄

Only the top-level struct passed to orderfields is reordered. Nested structs retain their current order.

Related Structs functions

fieldnames · getfield · isfield · rmfield · setfield · struct · structfun

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how orderfields is executed, line by line, in Rust.

  • View the source for orderfields 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.

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
  • How orderfields works
  • Does RunMat run orderfields on the GPU?
  • GPU memory and residency
  • Examples
  • How to sort struct fields alphabetically
  • Match the field order of another struct
  • Reorder fields with a cell array of names
  • Reorder fields with an index vector
  • Apply a custom order to every element of a struct array
  • Sort fields in descending alphabetical order
  • Using orderfields with coding agents
  • FAQ
  • Related Structs functions
  • Open-source implementation
  • About RunMat