5

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!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

what if I had much more fields like x,y,z etc. is there an efficient way to write this condition? because for just one condition isempty(s.x) it does not remove empty fields
maybe structfun is applicable...
actually I was thinking about the following, that I have at first A.B the whole with data. then i apply a condition for A.B.().y > 3 and if so save in a new structure, from which I got this empty A.B.(1,2) (let's say A.B.(1,2).y = 2). is there maybe a better way to avoid the empty fields in the structure at once?
problem is comparing a number with an empty field will yield an empty result. I suggest first filtering the empty ones out, and then applying your condition.
I am not sure if I understand well, but if so, then .. empty fields are the effect of applying my condition. Before all the fields had values, and due to the fact 2<3 I got empty fields.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.