orderfields

Reorders the fields of a structure.

Category: Language Fundamentals > Data Types

Syntax

sOut = orderfields(s)

Sorts the fields alphabetically.

sOut = orderfields(s, s2)

Uses the field order of structure s2, which must have the same field names.

sOut = orderfields(s, perm)

Reorders by the permutation vector perm.

[sOut, p] = orderfields(___)

Also returns the permutation vector.

Description

Only the order changes; values and field names stay the same. Alphabetical sorting is useful before comparing or displaying structures, and matching another structure's order lets you concatenate structure arrays that were built in different orders.

Input arguments

s
Structure or structure array.
s2 / c / perm
Another structure, a cell array of field names, or a vector of indices giving the new order.

Output arguments

sOut
Structure with the same data and the new field order.
p
Column vector: the permutation applied to the original order.

Example

s = struct('z', 1, 'a', 2, 'm', 3);
orderfields(s)
[~, p] = orderfields(s);
p'
orderfields(s, [3 1 2])
Output
ans = struct with fields:

    a: 2
    m: 3
    z: 1
ans = 1×3

     2     3     1
ans = struct with fields:

    m: 3
    z: 1
    a: 2

See also

fieldnames struct rmfield setfield isfield