Programming Previous page   Next Page

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:

Now entering

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:

The 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 names.

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).billing and patient(3).test contain empty matrices.

Building Structure Arrays Using the struct Function

You can preallocate an array of structures with the struct 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 temp and rainfall. Three different methods for allocating such an array are shown in this table.

Method
Syntax
Initialization
struct
weather(3) = struct('temp', 72, ...   'rainfall', 0.0);
weather(3) is initialized with the field values shown. The fields for the other structures in the array, weather(1) and weather(2), are initialized to the empty matrix.
struct with repmat
weather = repmat(struct('temp', ...   72, 'rainfall', 0.0), 1, 3);
All structures in the weather array are initialized using one set of field values.
struct with cell array syntax
weather = ...
struct('temp', {68, 80, 72}, ...   'rainfall', {0.2, 0.4, 0.0});
The structures in the weather array are initialized with distinct field values specified with cell arrays.

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.


Previous page  Structures Accessing Data in Structure Arrays Next page

© 1994-2005 The MathWorks, Inc.