| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
s = setfield(s, 'field', v)
s = setfield(s, {i,j}, 'field', {k},
v)
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 Guidelines for Naming Structure Fieldsfor help on creating valid field names.
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.
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 =
tedThe 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 73getfield, fieldnames, isfield, orderfields, rmfield, dynamic field names
![]() | setenv | setinterpmethod | ![]() |

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 |