# orderfields

Order fields of structure array

## Syntax

`s = orderfields(s1)s = orderfields(s1, s2)s = orderfields(s1, c)s = orderfields(s1, perm)[s, perm] = orderfields(...)`

## Description

`s = orderfields(s1)` orders the fields in `s1` so that the new structure array `s` has field names in ASCII dictionary order.

`s = orderfields(s1, s2)` orders the fields in `s1` so that the new structure array `s` has field names in the same order as those in `s2`. Structures `sl` and `s2` must have the same fields.

`s = orderfields(s1, c)` orders the fields in `s1` so that the new structure array `s` has field names in the same order as those in the cell array of field name strings `c`. Structure `s1` and cell array `c` must contain the same field names.

`s = orderfields(s1, perm)` orders the fields in `s1` so that the new structure array `s` has fieldnames in the order specified by the indices in permutation vector `perm`.

If `s1` has `N` fieldnames, the elements of `perm` must be an arrangement of the numbers from `1` to `N`. This is particularly useful if you have more than one structure array that you would like to reorder in the same way.

`[s, perm] = orderfields(...)` returns a permutation vector representing the change in order performed on the fields of the structure array that results in `s`.

## Examples

Create a structure `s`. Then create a new structure from `s`, but with the fields ordered alphabetically:

```s = struct('b', 2, 'c', 3, 'a', 1) s = b: 2 c: 3 a: 1 snew = orderfields(s) snew = a: 1 b: 2 c: 3```

Arrange the fields of `s` in the order specified by the second (cell array) argument of `orderfields`. Return the new structure in `snew` and the permutation vector used to create it in `perm`:

```[snew, perm] = orderfields(s, {'b', 'a', 'c'}) snew = b: 2 a: 1 c: 3 perm = 1 3 2```

Now create a new structure, `s2`, having the same fieldnames as `s`. Reorder the fields using the permutation vector returned in the previous operation:

```s2 = struct('b', 3, 'c', 7, 'a', 4) s2 = b: 3 c: 7 a: 4 snew = orderfields(s2, perm) snew = b: 3 a: 4 c: 7```

collapse all

### Tips

`orderfields` only orders top-level fields. It is not recursive.