Getting Started |
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
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,
which produces a numeric row vector containing all the scores.
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.
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:
function avg = avgscore(testscores, student, first, last) for k = first:last scores(k) = testscores.(student).week(k); end avg = sum(scores)/(last - first + 1);
You can run this function using different values for the dynamic field student
:
avgscore(testscores, 'Ann Lane', 1, 20) ans = 83.5000 avgscore(testscores, 'William King', 1, 20) ans = 92.1000
Characters and Text | Scripts and Functions |
© 1994-2005 The MathWorks, Inc.