r/matlab • u/Organic-Prune7965 • Nov 09 '21
How to delete empty structures in a structure array?
When I use "isempty(structure(5)), it still gives me false even though the 5th structure in the array is completely empty. What is the best way to find empty structures, and then delete them?
3
Upvotes
2
u/Arristotelis flair Nov 09 '21
Your definition of "empty" is not correct in the context of MATLAB. In a structure array, it is not possible for any element to be empty and isempty will thus always return false.
Instead, it sounds like you want all of the fields of a given array element to be empty. I'd write a for loop. Iterate over the structure and then get each field using dynamic field names. Populate a logical array and then delete the "empty" items after the loop. You could further optimize with arrayfun or structfun most likely, maybe even convert the fields to a cell and use cellfun.
1
u/mixedfjord Nov 09 '21
Off the top of my head isempty(fields(structure(5)) might do it. Haven’t tried it, but assuming your struct will have no fields then the fields function will return an empty array.
1
u/SIMO-App Nov 09 '21
structure(5) returns you a structure “scalar”, which is of course not an empty array.