fieldnames

Names of the fields of a struct or the properties of an object.

Category: Language Fundamentals > Data Types

Syntax

names = fieldnames(S)

Returns the field names as a cell array of character vectors.

Description

fieldnames is the usual way to loop over a struct: for k = 1:numel(f), s.(f{k}) ... end reads each field by dynamic name.

The result is a column, so transpose it with ' if a row is more convenient.

Input arguments

S
Structure (or an object).

Output arguments

names
Column cell array with one name per field, in the order the fields were created.

Example

Listing and looping

s = struct('p', 1, 'q', 'text');
f = fieldnames(s)
for k = 1:numel(f)
    fprintf('%s is a %s\n', f{k}, class(s.(f{k})));
end
Output
f = 2×1 cell

    {'p'}
    {'q'}
p is a double
q is a char

See also

isfield rmfield getfield setfield struct orderfields