setfield - Set value of structure array field

Syntax

s = setfield(s, 'field', v)
s = setfield(s, {i,j}, 'field', {k}, v)

Description

s = setfield(s, 'field', v), where s is a 1-by-1 structure, sets the contents of the specified field to the value v. If field is not an existing field in structure s, the MATLAB® software creates that field and assigns the value v to it. This is equivalent to the syntax s.field = v.

s = setfield(s, {i,j}, 'field', {k}, v) sets the contents of the specified field to the value v. If field is not an existing field in structure s, MATLAB creates that field and assigns the value v to it. This is equivalent to the syntax s(i,j).field(k) = v. 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.

See Naming conventions for Structure Field Names for guidelines to creating valid field names.

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 MATLAB 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;

You can change the name field of mystr(2,1) using

mystr = setfield(mystr, {2,1}, 'name', 'ted');
mystr(2,1).name

ans =

ted

The following example sets fields of a structure using setfield with variable and quoted field names and additional subscripting arguments.

class = 5;   student = 'John_Doe';
grades_Doe = [85, 89, 76, 93, 85, 91, 68, 84, 95, 73];
grades = [];

grades = setfield(grades, {class}, student, 'Math', ... 
   {10, 21:30}, grades_Doe);

You can check the outcome using the standard structure syntax.

grades(class).John_Doe.Math(10, 21:30)

ans =

    85   89   76   93   85   91   68   84   95   73

See Also

getfield, fieldnames, isfield, orderfields, rmfield, Using Dynamic Field Names

  


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