Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing empty structure fields Matlab

I'm facing the following problem: I have an array of structures like:

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

And I would like to remove the empty 2. row from this structure, so that in the end I get fields for (1,1) and (1,3). I was trying to convert to cells, remove and then back to structure, but this way I had to retype names of fields. How is it possible to do it? Can it be done without conversion from structures?

tia!

like image 471
beginh Avatar asked Nov 04 '22 18:11

beginh


1 Answers

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

empty_elems = arrayfun(@(s) isempty(s.x) & isempty(s.y),A.B)

returns: [0 1 0]

or

empty_elems = arrayfun(@(s) all(structfun(@isempty,s)), A.B);

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

Then remove them using logical indexing:

A.B(empty_elems) = [];

Full solution to your problem in comments:

% find array elements that have all fields empty:
empty_elems = arrayfun(@(s) all(structfun(@isempty,s)), A.B);

% copy non-empty elements to a new array `C`:
C = A.B(~empty_elems);

% find elements of C that have y field >3
gt3_elems = arrayfun(@(s) s.y<3,C);

% delete those form C:
C(gt3_elems) = [];

execute this code step by step and analyze the intermediary variables to understand what's happening. It should be fairly clear.

like image 182
Gunther Struyf Avatar answered Nov 09 '22 15:11

Gunther Struyf