Programming |
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
Accessing Data in Structure Arrays | Finding the Size of Structure Arrays |
© 1994-2005 The MathWorks, Inc.