Programming and Data Types    

Accessing Data in Structure Arrays

Using structure array indexing, you can access the value of any field or field element in a structure array. Likewise, you can assign a value to any field or field element. For the examples in this section, consider this structure array.

You can access subarrays by appending standard subscripts to a structure array name. For example, the line below results in a 1-by-2 structure array.

The first structure in the mypatients array is the same as the first structure in the patient array.

To access a field of a particular structure, include a period (.) after the structure name followed by the field name.

To access elements within fields, append the appropriate indexing mechanism to the field name. That is, if the field contains an array, use array subscripting; if the field contains a cell array, use cell array subscripting, and so on.

Use the same notations to assign values to structure fields, for example,

You can extract field values for multiple structures at a time. For example, the line below creates a 1-by-3 vector containing all of the billing fields.

Similarly, you can create a cell array containing the test data for the first two structures.

Accessing Field Values Using setfield and getfield

Direct indexing is usually the most efficient way to assign or retrieve field values. If, however, you only know the field name as a string - for example, if you have used the fieldnames function to obtain the field name within an M-file - you can use the setfield and getfield functions to do the same thing.

getfield obtains a value or values from a field or field element

where the field_index is optional, and array_index is optional for a 1-by-1 structure array. The function syntax corresponds to

For example, to access the name field in the second structure of the patient array, use:

Similarly, setfield lets you assign values to fields using the syntax


 Building Structure Arrays Finding the size of Structure Arrays