I want to construct an struct object with three properties:
arg1 = 42;
arg2 = 'test';
arg3 = cell(0);
But if I try to initialize that object:
struct('arg1', arg1, 'arg2', arg2, 'arg3', arg3);
It returns an empty struct:
ans =
0×0 empty struct array with fields:
arg1
arg2
arg3
I figured out the empty cell is the culprit, so if i initialize it without the empty cell it returns a correct value:
ans =
struct with fields:
arg1: 42
arg2: 'test'
arg3: []
But I need my code to work with empty cells, and I don't know if or where they will be in one of the fields.
Is there a way to get out of this problem?
This is documented behaviour:
s = struct(field,value)
creates a structure array with the specifiedfield
andvalues
. Thevalue
input argument can be any data type, such as a numeric, logical, character, or cell array.
If any of the
value
inputs is a nonscalar cell array, thens
has the same dimensions as the nonscalar cell array. [...]If
value
is an empty cell array{}
, thens
is an empty (0-by-0) structure. To specify an empty field and keep the values of the other fields, use[]
as a value input instead
The take-away for you is the last line.
To get around this, you will have to do checks like
if iscell( argX ) && isempty( argX )
argX = [];
end
If you always just have 3 items in your struct then this is fairly simple to implement.