MATLAB Function Reference |
Set value of structure array field
Syntax
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
. 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
. 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.
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 Technical Note 32236 for information about using dynamic field names versus the getfield
and setfield
functions.
Examples
You can change the name
field of mystr(2,1)
using
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.
See Also
getfield
, fieldnames
, isfield
, orderfields
, rmfield
, dynamic field names
setdiff | setpref |
© 1994-2005 The MathWorks, Inc.