struct
The struct function constructs a structure (or structure array) from field/value pairs. It is an alternative to building a structure incrementally with dot assignment, useful when the fields are known up front or when a structure array of identical schema is needed.
s = structreturns a 1×1 structure with no fieldss = struct(field,value)creates a single-field structures = struct(field1,value1,...,fieldN,valueN)creates a structure with multiple fields in one calls = struct([])returns a 0×0 empty structure with no fields
Field Names
- field is a char vector or
stringscalar that obeys the rules of variable names - Duplicate field names raise an error
Structure Arrays from Cell Arrays
When value is a cell array, struct does not put the cell into a single field. Instead, it spreads the cells across a structure array: each cell becomes the field value of one element, and the array’s size matches the cell’s size.
- To store a cell array as a single field value, wrap it in another cell:
struct('f',{{1,2,3}})produces a scalar struct whose fieldfis the inner 1×3 cell.
>> s = struct('name',{'Alice','Bob'},'age',{30,42})
s =
1x2 struct array with fields:
name
age
>> s(2)
ans =
struct with fields:
name: 'Bob'
age: 42When several values are cell arrays, they must all have the same size; that size becomes the size of the resulting structure array.