setfield

Sets the value of field f in the stucture s to the value v.

Syntax

R = setfield(s,f,v)

R = setfield(s,idx,f,v)

R = setfield(s,idx1,f1,idx2,...fn,idxn,v)

Inputs

s
Struct.
Type: struct
Dimension: scalar | vector | matrix
f
Field.
Type: char | string
Dimension: string
v
Value to set.
Type: double | integer | char | string | logical | struct | cell
Dimension: scalar | string | vector | matrix
idx
The index (or indices) of the element in the struct array to modify. Must be stored in a cell array.
Type: cell
Dimension: scalar | vector | matrix

Outputs

R
Resulting structure.

Examples

Simple setfield example:
a = struct('name', 'Bob', 'age', 33);
R = setfield(a, 'age', 34)
R = struct [
age: 34
name: Bob
]
Simple setfield example:
a = struct('name', {'Bob', 'Dave'}, 'age', {33, 44});
R = setfield(a, {1}, 'age', 34)
R(1)
R = struct [
Struct array of size 1 x 2 with fields:
age
name
]
ans = struct [
age: 34
name: Bob
]
setfield example with nested struct:
a.name = 'Bob';
a(2).name.dateofbirth = struct('date',{11,25,1985});
a = setfield(a,{2},'name','dateofbirth',{3},'date',{10,25,1985});
a(2).name(2).dateofbirth(3)
ans = struct [
  date:
  {
        [1,1] 10
        [1,2] 25
        [1,3] 1985
  }
]