Hannesh
Hannesh

Reputation: 7488

Matlab: Names of the variables in a struct

Given a struct from a function with a number of unknown fields, how do I get the name of each field?

For example:

s = struct;
s.hello = 'world';
s.foo = 12;
s.bar = [ 1 2 3 ];

I want the name of s(1), s(2) and s(3). In this case I would get 'hello', 'foo' and 'bar'.

Upvotes: 4

Views: 5259

Answers (1)

Jonas
Jonas

Reputation: 74940

You're looking for FIELDNAMES

fieldnames(s)
fn = 
    'hello'
    'foo'
    'bar'

Note that fn is a cell array, so you get the 'foo' as fn{2}

Upvotes: 6

Related Questions