Check if any field in a given structure is empty

315 views (last 30 days)
ihrram on 6 Mar 2017
Commented: Dominique on 16 Feb 2022
Hello everyone,
I have a structure with quite some fields and I want to check, if any of the fields are empty. Is there a way to do this without checking for each field individually?
Currently I have an if statement with many ORs to do this:
if isempty(structure.field1) || isempty(structure.field2)
and so on
I tried to do the same with
but obviously the fieldnames are not empty.

Accepted Answer

Walter Roberson
Walter Roberson on 6 Mar 2017
any( structfun(@isempty, YourStructure) )
Walter Roberson
Walter Roberson on 9 Mar 2019
if length(a.table) >= 20 & ~isempty(a.table{20})

Sign in to comment.

More Answers (2)

Ross Nye
Ross Nye on 30 Nov 2017
I'm going to leave this here in case someone comes across this page looking for a similar answer to what I was.
I have a 1xN struct with many fields. One particular field was supposed to be boolean, but only the falses had been entered and the rest were []. The above answers didn't seem to help me, but I did find something on Reddit which did.
emptyIndex = find(arrayfun(@(MyStruct) isempty(MyStruct.myField),MyStruct));
I can then use emptyIndex to set the fields to true as needed.
HTH someone.
Andres on 27 May 2021
This will work as well
for a struct array MyStruct with field myField.
Note in many cases you don't need find for indexing.
Example: fill empty fields with 0s
MyStruct(3).myField = 123;
hasNone = cellfun(@isempty,{MyStruct.myField});
[MyStruct(hasNone).myField] = deal(0);

Sign in to comment.

LeChat on 13 Aug 2020
It might be a bit dirty because I use a loop but it works:
for ii=1:numel(MyStruct)
if isempty(MyStruct(ii).FieldName)
ind=[ind, ii];
Then ind contains all the indexes where the structure field is empty.
For instance if you then want to remove them from the structure:
Hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!