What does the orderfields function do in MATLAB / RunMat?
orderfields(S) reorders the field definitions of a scalar struct or struct array. By default the fields
are sorted alphabetically. Optional arguments let you match the order of another struct, provide an explicit
list of names, or supply a permutation vector.
How does the orderfields function behave in MATLAB / RunMat?
- 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.
orderfields Function GPU Execution Behaviour
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 residency in RunMat (Do I need gpuArray?)
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 of using the orderfields function in MATLAB / RunMat
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);
aligned now has fields ordered x, then y. The permutation vector order is [2 1], indicating that field 2 (x) moved to the first position.
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]}
The permutation vector perm is [2 1], which you can reuse with orderfields(otherStruct, perm) for any struct that contains the same fields.
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'}
flip reverses the alphabetical list returned by fieldnames, so orderfields applies the desired descending order without needing a special mode argument.
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.
See Also
struct, fieldnames, getfield, setfield, rmfield
Source & Feedback
- Implementation:
crates/runmat-runtime/src/builtins/structs/core/orderfields.rs - Found a behavioural mismatch? Please open an issue at
https://github.com/runmat-org/runmat/issues/new/choose.