Growing an array, e.g. through x = [x, a]
in a loop, is usually frowned upon in Matlab programming, because it leads to one or more resize operations, and therefore preallocation is usually the better option. However, in some contexts, for example as a reduction assignment in a parfor
block, it can have advantages. For that purpose, the array has to be created as zero-size. For numerical arrays, the expression for that is []
, for cell arrays {}
.
For struct arrays, it is not so clear cut. For example initialization as struct()
does not create a zero-size struct array, but a 1x1 struct array with no fields. This leads to the error
Error using horzcat
Number of fields in structure arrays being concatenated do not match.
Concatenation of structure arrays requires that these arrays have the same set of fields.
while growing, because the field structure of appended structs is incompatible with the "no fields" struct.
How to initialize a zero-size struct array for growing?