Tutorial

How to Get the Field Names of a Struct Array in MATLAB

The function fieldnames returns the field names of a struct array.

Preparation

Create a struct array using the following code:

names = {'Peter Pan','Wendy Darling'};
sexes = {'M','F'};
ages = {11,12};
A = struct('name', names, 'sex', sexes, 'age', ages);

Syntax

names = fieldnames(s) stores in the cell arrray names the field names of the struct array s.

% Get the field names of A
names = fieldnames(A);
If s is not a struct array or an object, MATLAB generates an error.

Further reading

I recommend the following books to learn more on struct arrays in MATLAB:

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. Struct arrays, cell arrays, and other data types, are explained clearly in the eighth chapter.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Chapter 11 explains excellently struct arrays, cell arrays, and character arrays, among other data types.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

doc fieldnames;

Source code

I hope you have learned how to get the field names of a struct array in MATLAB. The source code developed in this tutorial is available at this page.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.