Products & Services Industries Academia Support User Community Company

Learn more about MATLAB   

getfield - Field of structure array

Syntax

f = getfield(s,'field')
f = getfield(s, {i,j}, 'field', {k})

Description

f = getfield(s,'field'), where s is a 1-by-1 structure, returns the contents of the specified field. This is equivalent to the syntax f = s.field.

If s is a structure having dimensions greater than 1-by-1, getfield returns the first of all output values requested in the call. That is, for structure array s(m,n), getfield returns f = s(1,1).field.

f = getfield(s, {i,j}, 'field', {k}) returns the contents of the specified field. This is equivalent to the syntax f = s(i,j).field(k). All subscripts must be passed as cell arrays — that is, they must be enclosed in curly braces (similar to{i,j} and {k} above). Pass field references as strings.

Remarks

In many cases, you can use dynamic field names in place of the getfield and setfield functions. Dynamic field names express structure fields as variable expressions that the MATLAB software evaluates at run-time. See Solution 1-19QWG for information about using dynamic field names versus the getfield and setfield functions.

Examples

Given the structure

mystr(1,1).name = 'alice';
mystr(1,1).ID = 0;
mystr(2,1).name = 'gertrude';
mystr(2,1).ID = 1

Then the command f = getfield(mystr, {2,1}, 'name') yields

f =
   gertrude

To list the contents of all name (or other) fields, embed getfield in a loop.

for k = 1:2
    name{k} = getfield(mystr, {k,1}, 'name');
end
name

name = 

    'alice'    'gertrude'

The following example starts out by creating a structure using the standard structure syntax. It then reads the fields of the structure, using getfield with variable and quoted field names and additional subscripting arguments.

class = 5;     student = 'John_Doe';
grades(class).John_Doe.Math(10,21:30) = ...
             [85, 89, 76, 93, 85, 91, 68, 84, 95, 73];

Use getfield to access the structure fields.

getfield(grades, {class}, student, 'Math', {10,21:30})

ans =
   85   89   76   93   85   91   68   84   95   73

See Also

setfield, fieldnames, isfield, orderfields, rmfield, dynamic field names

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS