Assuming I have a struct S
of size 0x1 with the fields a
and b
, what is the most elegant way to add a field c
to it?
Usually I am able to do it like this:
S = struct('a',0,'b',0); %1x1 struct with fields a,b
S.c = 0
However, if I receive an empty struct this does not work anymore:
S = struct('a',0,'b',0);
S(1) = []; % 0x1 struct with fields a,b
S.c = 0;
% A dot name structure assignment is illegal when the structure is empty.
% Use a subscript on the structure.
I have thought of two ways to deal with this, but both are quite ugly and feel like workarounds rather than solutions. (Note the possibility of a non-empty struct should also be dealt with properly).
- Adding something to the struct to ensure it is not empty, adding the field, and making the struct empty again
- Initializing a new struct with the required fieldnames, filling it with the data from the original struct, and overwriting the original struct
I realize that it may be odd that I care about empty structs, but unfortunately part of the code that is not managed by me will crash if the fieldname does not exist. I have looked at help struct
, help subsasgn
and also searched for the given error message but so far I have not yet found any hints. Help is therefore much appreciated!