Getting Started Previous page   Next Page

Structures

Structures are multidimensional MATLAB arrays with elements accessed by textual field designators. For example,

creates a scalar structure with three fields.

Like everything else in MATLAB, structures are arrays, so you can insert additional elements. In this case, each element of the array is a structure with several fields. The fields can be added one at a time,

or an entire element can be added with a single statement.

Now the structure is large enough that only a summary is printed.

There are several ways to reassemble the various fields into other MATLAB arrays. They are all based on the notation of a comma-separated list. If you type

it is the same as typing

This is a comma-separated list. Without any other punctuation, it is not very useful. It assigns the three scores, one at a time, to the default variable ans and dutifully prints out the result of each assignment. But when you enclose the expression in square brackets,

it is the same as

which produces a numeric row vector containing all the scores.

Similarly, typing

just assigns the names, one at a time, to ans. But enclosing the expression in curly braces,

creates a 1-by-3 cell array containing the three names.

And

calls the char function with three arguments to create a character array from the name fields,

Dynamic Field Names

The most common way to access the data in a structure is by specifying the name of the field that you want to reference. Another means of accessing structure data is to use dynamic field names. These names express the field as a variable expression that MATLAB evaluates at run-time. The dot-parentheses syntax shown here makes expression a dynamic field name:

Index into this field using the standard MATLAB indexing syntax. For example, to evaluate expression into a field name and obtain the values of that field at columns 1 through 25 of row 7, use

Dynamic Field Names Example.   The avgscore function shown below computes an average test score, retrieving information from the testscores structure using dynamic field names:

You can run this function using different values for the dynamic field student:


Previous page  Characters and Text Scripts and Functions Next page

© 1994-2005 The MathWorks, Inc.