Documentation Center

  • Trial Software
  • Product Updates
我们为许可用户提供了部分翻译好的中文文档。您只需登录便可查阅这些文档

getfield

Field of structure array

Syntax

value = getfield(struct, 'field')
value = getfield(struct,{sIndx1,...,sIndxM},'field',{fIndx1,...,fIndxN})

Description

value = getfield(struct, 'field'), where struct is a 1-by-1 structure, returns the contents of the specified field, equivalent to value = struct.field. Pass field references as strings.

value = getfield(struct,{sIndx1,...,sIndxM},'field',{fIndx1,...,fIndxN}) returns the contents of the specified field, equivalent to value = struct(sIndx1,...,sIndxM).field(fIndx1,...,fIndxN). The getfield function supports multiple sets of field and fIndx inputs, and all Indx inputs are optional. If structure struct or any of the fields is a nonscalar structure, and you do not specify an Indx, the getfield function returns the values associated with the first index. If you specify a single colon operator for an fIndx input, enclose it in single quotation marks: ':'.

Examples

The what function returns a structure array that describes the MATLAB® files in the current folder. Find the files with the .m extension:

files = getfield(what, 'm');

To perform the same task by indexing requires that you create a temporary variable:

templist = what;
files = templist.m;
 

Find values within a structure that contains nested fields:

level = 5;
semester = 'Fall';
subject = 'Math';
student = 'John_Doe';
fieldnames = {semester subject student};

% Add data to a structure named grades.
grades(level).(semester).(subject).(student)(10,21:30) = ...
             [85, 89, 76, 93, 85, 91, 68, 84, 95, 73];

% Retrieve the data added.
getfield(grades, {level}, fieldnames{:}, {10,21:30})
 

Using the structure defined in the previous example, find all values in the tenth row of the specified field:

getfield(grades, {level}, fieldnames{:}, {10,':'})

More About

expand all

Tips

  • For most cases, retrieve data from a structure array by indexing rather than using the getfield function. For more information, see Access Data in a Structure Array and Generate Field Names from Variables.

  • Call getfield to simplify references to structure arrays with nested fields, or to avoid creating unnecessary temporary variables, as shown in the Examples section.

See Also

| | | |

Was this topic helpful?