Building Structure Arrays
You can build structures in two ways:
Building Structure Arrays Using Assignment Statements
You can build a simple 1-by-1 structure array by assigning data to individual fields. MATLAB automatically builds the structure as you go along. For example, create the 1-by-1
patient structure array shown at the beginning of this section:
at the command line results in
patient is an array containing a structure with three fields. To expand the structure array, add subscripts after the structure name:
patient structure array now has size
[1 2]. Note that once a structure array contains more than a single element, MATLAB does not display individual field contents when you type the array name. Instead, it shows a summary of the kind of information the structure contains:
You can also use the
fieldnames function to obtain this information.
fieldnames returns a cell array of strings containing field
As you expand the structure, MATLAB fills in unspecified fields with empty matrices so that
For example, entering
patient(3).name = 'Alan Johnson' expands the
patient array to size
[1 3]. Now both
patient(3).test contain empty matrices.
Field sizes do not have to conform for every element in an array. In the |
Building Structure Arrays Using the struct Function
You can preallocate an array of structures with the
function. Its basic form is
where the arguments are field names and their corresponding values. A field value can be a single value, represented by any MATLAB data construct, or a cell array of values. All field values in the argument list must be of the same scale (single value or cell array).
You can use different methods for preallocating structure arrays. These methods differ in the way in which the structure fields are initialized. As an example, consider the allocation of a 1-by-3 structure array,
weather, with the structure fields
rainfall. Three different methods for allocating such an array are shown in this table.
||All structures in the
||The structures in the
Memory Requirements for Structures
You do not necessarily need a contiguous block of memory to store a structure. The memory for each field in the structure needs to be contiguous, but not the entire structure itself.
|Structures||Accessing Data in Structure Arrays|
© 1994-2005 The MathWorks, Inc.