Skip to Main Content Skip to Search
Product Documentation

setfield - Assign values to structure array field

Syntax

s = setfield(s,'field',value)
s = setfield(s,{sIndx1,...,sIndxM},'field',{fIndx1,...,fIndxN},value)

Description

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: ':'.

Tips

Examples

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,':'}, []);

See Also

fieldnames | getfield | isfield | orderfields | rmfield

How To

  


Free MATLAB Interactive Kit

Explore how to use MATLAB to make advancements in engineering and science.


Download free kit

Trials Available

Try the latest version of MATLAB and other MathWorks products.


Get trial software
 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS