| Contents | Index |
s = setfield(s,'field',value)
s = setfield(s,{sIndx1,...,sIndxM},'field',{fIndx1,...,fIndxN},value)
s = setfield(s,'field',value), where s is a 1-by-1 structure, sets the contents of the specified field, equivalent to s.field = value. If s does not contain the specified field, the setfield function creates the field and assigns the specified value. Pass field references as strings.
s = setfield(s,{sIndx1,...,sIndxM},'field',{fIndx1,...,fIndxN},value) sets the contents of the specified field, equivalent to s(sIndx1,...,sIndxM).field(fIndx1,...,fIndxN) = value. The setfield function supports multiple sets of field and fIndx inputs. If structure s or any of the fields is a nonscalar structure, the Indx inputs associated with that input are required. Otherwise, the Indx inputs are optional. If you specify a single colon operator for an index input, enclose it in single quotation marks: ':'.
For most cases, add data to a structure array by indexing rather than using the setfield function. For more information, see Access Data in a Structure Array and Generate Field Names from Variables.
Call setfield to simplify references to structure arrays with nested fields, as shown in the Examples section.
Add values to a structure that contains nested fields:
grades = [];
level = 5;
semester = 'Fall';
subject = 'Math';
student = 'John_Doe';
fieldnames = {semester subject student}
newGrades_Doe = [85, 89, 76, 93, 85, 91, 68, 84, 95, 73];
grades = setfield(grades, {level}, ...
fieldnames{:}, {10, 21:30}, ...
newGrades_Doe);
% View the new contents.
grades(level).(semester).(subject).(student)(10, 21:30)Using the structure defined in the previous example, remove the tenth row of the specified field:
grades = setfield(grades, {level}, fieldnames{:}, {10,':'}, []);fieldnames | getfield | isfield | orderfields | rmfield

Explore how to use MATLAB to make advancements in engineering and science.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |