How to make a 1x0 struct array
S = struct('a',cell(1,0),'b',cell(1,0), 'c', cell(1,0))
S =
1×0 empty
struct array with fields:
a
b
c
Addendum: why does this create a 1x0 struct array?
TL;DR
When defining a structure array using cell arrays, the structure array takes on the size of the cell array (see demos G and J below).
Deep dive into structure size
This can get a little confusing.
The first thing to understand is the difference between a scalar structure and a structure array. By definition, a scalar structure is a structure with size 1x1 and therefore cannot be empty. The size of a structure array is determined by its content which can result in dimensions that are conterintuitive, at least for me.
The syntax s=struct(field,value) produces a scalar structure iff, - value is not a cell array
- or value is a scalar cell array
If value is a nonscalar cell array then S is a structure array with the same size as value. S(i) shows the value for element i.
S = struct('a', num2cell([1 2; 3 4; 5 6]));
If value is an empty cell, then S is an empty structure array with the specified field
Here's where things get weird. When struct() contains no inputs, a scalar structure is created that has no fields and therefore may appear to be empty but has a size of 1x1.
But if the structure is defined by an empty double array then the structure is empty and is no longer scalar. This is because, by definition, a scalar value has a size 1x1 and isn't empty.
This syntax either creates a scalar structure with multiple fields or a structure array with multiple fields following the same rules as above. The result is a scalar structure iff, - all values are not cell arraya
- or cell array values are scalar
S = struct('a', 'foo', 'b', [98 97 114])
S = struct('a', {'foo'}, 'b', {[98,97,114]})
If any value inputs are nonscalar cell arrays, then S is a structure array with the same size as the nonscalar cell array. All nonscalar cell arrays in value must have the same size.
S = struct('a', {'foo'}, 'b', num2cell([98,97,114]))
S = struct('a', num2cell(1:5), 'b', num2cell(1:6))
If any value is an empty cell array then S is an empty structure array. Note the word any. Even if other fields are non-empty, S will be empty.
S = struct('a',{},'b',cell(0,0))
S = struct('a', 'foo', 'b', [98,97,114], 'c', {})
Crazy, right? To tell Matlab hey, I wanted that field to be empty!!, define the field using an empty double array,
S = struct('a', 'foo', 'b', [98,97,114], 'c', [])
Lastly, and coming full circle, empty arrays can have different dimensions as long as one of the dimensions is 0. To create an nx0 structure array,
S = struct('a', cell(n,0), 'b', (cell(n,0)));
Best Answer