Assign values to structure array field


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


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}, ... 

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

More About

collapse all


Introduced before R2006a

Was this topic helpful?