Removing Empty Matlab Structure Fields

I ran into the following problem: I have an array of structures like:

AB(1,1).x = 'string' AB(1,1).y = 12 AB(1,2).x = [] AB(1,2).y = [] AB(1,3).x = 'string2' AB(1,3).y = 4 

And I would like to remove the empty 2. line from this structure, so in the end I get the fields for (1,1) and (1,3). I tried to convert to cells, delete, and then return to the structure, but this way I had to re-specify the field names. How is this possible? Can this be done without conversion from structures?

TIA!

+4
source share
1 answer

Use a loop or arrayfun to determine which elements of the array are empty:

 empty_elems = arrayfun(@(s) isempty(sx) & isempty(sy),AB) 

returns: [0 1 0]

or

 empty_elems = arrayfun(@(s) all(structfun(@isempty,s)), AB); 

which checks if all fields are empty (use any instead of all to check if any element is empty and not all).

Then delete them using logical indexing :

 AB(empty_elems) = []; 

A complete solution to your problem in the comments:

 % find array elements that have all fields empty: empty_elems = arrayfun(@(s) all(structfun(@isempty,s)), AB); % copy non-empty elements to a new array `C`: C = AB(~empty_elems); % find elements of C that have y field >3 gt3_elems = arrayfun(@(s) sy<3,C); % delete those form C: C(gt3_elems) = []; 

follow this code step by step and analyze the intermediate variables to understand what is going on. This should be clear enough.

+1
source

All Articles