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
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
S | Any | Yes | — | Input struct or struct array. |
order | Any | No | — | Reference struct, field-name list, or permutation vector. |
Returns
| Name | Type | Description |
|---|---|---|
S | Any | Struct or struct array with reordered fields. |
P | NumericArray | Permutation vector mapping ordered fields to original positions. |
Returned values from orderfields depend on how many outputs the caller requests.
Errors
| Identifier | When | Message |
|---|---|---|
orderfields:TooManyInputs | More than two input arguments are supplied. | orderfields: expected at most two input arguments |
orderfields:InvalidInput | First argument is not a struct or struct array. | orderfields: first argument must be a struct or struct array |
orderfields:EmptyStructArray | Empty struct array is asked to adopt a non-empty reference order. | orderfields: empty struct arrays cannot adopt a non-empty reference order |
orderfields:NoFields | Ordering is requested for a struct array with no fields. | orderfields: struct array has no fields to reorder |
orderfields:InvalidStructArray | A struct-array element is not a struct. | orderfields: struct array element is not a struct |
orderfields:InvalidStructContents | Struct-array contents are not all structs. | orderfields: expected struct array contents to be structs |
orderfields:RebuildFailed | Rebuilding reordered struct array failed. | orderfields: failed to rebuild struct array |
orderfields:InvalidReference | Reference struct-array contains non-struct values. | orderfields: reference struct array element is not a struct |
orderfields:InvalidFieldNameList | Name-list entries are not scalar strings or character vectors. | orderfields: cell array elements must be a string or character vector |
orderfields:EmptyFieldName | Requested field-name list contains an empty name. | orderfields: field names must be nonempty |
orderfields:InvalidPermutation | Permutation vector does not include each field exactly once. | orderfields: index vector must permute every field exactly once |
orderfields:IndexNotInteger | Permutation vector contains non-integer entries. | orderfields: index vector must contain integers |
orderfields:IndexOutOfRange | Permutation vector index is outside valid field range. | orderfields: index vector element out of range |
orderfields:DuplicateIndex | Permutation vector contains duplicate positions. | orderfields: index vector contains duplicate positions |
orderfields:FieldMismatch | Requested field set does not exactly match struct fields. | orderfields: field names must match the struct exactly |
orderfields:UnknownField | Requested order references an unknown field. | orderfields: unknown field in requested order |
orderfields:DuplicateField | Requested field order includes duplicate names. | orderfields: duplicate field in requested order |
orderfields:MissingField | A field from the requested order is missing on the struct. | orderfields: field does not exist on the struct |
orderfields:InvalidOrderArgument | Second argument is not a supported order descriptor. | orderfields: unrecognised ordering argument |
orderfields:InternalError | Internal 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 behaviour
orderfields(S)sorts field names alphabetically using MATLAB's case-insensitive ordering. orderfields(S, referenceStruct)matches the order ofreferenceStruct. Both structs must contain the same field names.orderfields(S, {'b','a','c'})ororderfields(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.[T, P] = orderfields(S, ___)returns the reordered struct (or struct array)Tand a permutation vectorPwhose elements are the original 1-based field positions. ReusePto apply the same order to other structs that share the field set.- The function never copies field contents unnecessarily—values (including GPU handles) are re-used and remain resident.
- 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
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.