What Is the Definition of Scalar Structure?

 Accepted Answer

A scalar structure is an array of class struct for which the isscalar function returns true.

6 Comments

Could you add some explanation please? Multiple fields but singular indices?
A scalar structure can have no fields, one field, or many fields.
S = struct()
S = struct('foo', 1)
S = struct('foo', 1, 'bar', 2, 'baz', 3)
For each of those arrays S, isa(S, 'struct') & isscalar(S) returns true so they are each scalar structures.
N = dir(fullfile(matlabroot, 'toolbox', 'matlab', 'demos'))
isa(N, 'struct')
isscalar(N)
isa(N, 'struct') returns true but isscalar(N) returns false so N is not a scalar structure.
N = 17;
isa(N, 'struct')
isscalar(N)
isa(N, 'struct') returns false but isscalar(N) returns true so N is not a scalar structure.
N = ones(5);
isa(N, 'struct')
isscalar(N)
isa(N, 'struct') returns false and isscalar(N) returns false so N is not a scalar structure.
These all sound like ways to test whether a structure is scalar, rather than a definition of what a scalar structure actually is.
The simplest answer seems like it might be that a scalar (anything) is defined as having size 1x1, so any 1x1 structure (regardless of number or content of fields) would be scalar. Is this correct, or am I missing some nuance?
@Dandan: that is correct. As you say, the same rule applies to all standard MATLAB types, so:
1x1 struct = scalar struct
1x1 double = scalar double
1x1 cell = scalar cell
etc.
See the definition here:
It is very important to remember that the size of the structure is totally independent to how many fields it has!
@Stephen Cobeldick: how can the size of the structure be independent of how many fields it has? when you add another field, the structure becomes 1*2 and would fail the isscalar test right?
Nope. Adding a file folder to the drawer in a filing cabinet with one drawer doesn't change the fact that the filing cabinet has one drawer. It just means the drawer contains one more folder than it did before. Buying another one-drawer filing cabinet and stacking it on top of the first would change the number of drawers your filing system has available.
The analogy isn't perfect, because "each structure in the array must have the same number of fields and the same field names" and there's no limitation that the drawers in a filing cabinet must have the same number of file folders, but it's useful enough when talking about sizes.
The size of the struct is analogous to the number of drawers in your filing cabinet while the number of fields in your struct array (the length of the cell array returned by calling fieldnames on the struct) is the number of folders inside each drawer.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!