How to Check if a Struct Array Has a Field in MATLAB

The function isfield determines if a struct array includes a field with a certain name.


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);


tf = isfield(s,field) determines if the struct array s includes a field named field, and stores the result in the logical variable tf.

To check for multiple fields, specify the field names as a cell array of strings. In these cases tf(i) is true if field{i} is an existing field, false otherwise.

% Check if 'age' is a field of A
resultExample1 = isfield(A,'age');
% Check if 'birthdate' is a field of A
resultExample2 = isfield(A,'birthdate');
% Check which values are fields of A
values = {'name', 'sex', 'phone', 'email', 'age'};
resultExample3 = isfield(A,values);

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 isfield;

Source code

I hope you have learned how to check in MATLAB if a struct array has a field with a certain name. The source code developed in this tutorial is available at this page.


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