struct
Structure array
Description
A structure array is a data type that groups related data
using data containers called fields. Each field can contain any
type of data. Access data in a field using dot notation of the form
structName.fieldName
.
Creation
When you have data to put into a new structure, create the structure using dot notation to name its fields one at a time:
s.a = 1; s.b = {'A','B','C'}
s = struct with fields:
a: 1
b: {'A' 'B' 'C'}
Field names can contain ASCII letters (A–Z, a–z), digits (0–9), and underscores, and
must begin with a letter. The maximum length of a field name is
namelengthmax
.
You also can create a structure array using the struct
function,
described below. You can specify many fields simultaneously, or create a nonscalar
structure array.
Syntax
Description
s = struct
creates a scalar (1-by-1) structure with
no fields.
s = struct(
creates a structure array with the specified field and value. The
field
,value
)value
input argument can be any data type, such as a
numeric, logical, character, or cell array.
If
value
is not a cell array, or ifvalue
is a scalar cell array, thens
is a scalar structure. For instance,s = struct('a',[1 2 3])
creates a 1-by-1 structure, wheres.a = [1 2 3]
.If
value
is a nonscalar cell array, thens
is a structure array with the same dimensions asvalue
. Each element ofs
contains the corresponding element ofvalue
. For example,s = struct('x',{'a','b'})
returnss(1).x = 'a'
ands(2).x = 'b'
.If
value
is an empty cell array{}
, thens
is an empty (0-by-0) structure.
s = struct(field1,value1,...,fieldN,valueN)
creates a
structure array with multiple fields.
If none of the
value
inputs are cell arrays, or if allvalue
inputs that are cell arrays are scalars, thens
is a scalar structure.If any of the
value
inputs is a nonscalar cell array, thens
has the same dimensions as that cell array. Also, if two or morevalue
inputs are nonscalar cell arrays, then they all must have the same dimensions.For any
value
that is a scalar cell array or an array of any other data type,struct
inserts the contents ofvalue
in the relevant field for all elements ofs
. For example,s = struct('x',{'a','b'},'y','c')
returnss(1).x = 'a'
,s(2).x = 'b'
,s(1).y = 'c'
, ands(2).y = 'c'
.If any
value
input is an empty cell array,{}
, then outputs
is an empty (0-by-0) structure. To specify an empty field and keep the values of the other fields, use[]
as avalue
input instead.
s = struct([])
creates an empty (0-by-0) structure
with no fields.
s = struct(
creates a scalar
structure with field names and values that correspond to properties of
obj
)obj
. The struct
function does not
convert obj
, but rather creates s
as a
new structure. This structure does not retain the class information, so
private, protected, and hidden properties become public fields in
s
. The struct
function issues a
warning when you use this syntax.