amazon

16.4.14

Set field values at once in MATLAB

When setting values in a field of a struct array, I met errors.

First of all using the for statement:

>> a=struct()
a =
1x1 struct array with no fields.

>> for ii = 1:3
a(ii).field1 = ii;
end
>> a.field1
ans =
   1
ans =
   2
ans =
   3

Ok so for

Then I tried it with one line like:

>> a.field2 = 1:3

??? Incorrect number of right hand side elements in dot name assignment.
Missing [] around left hand side is a likely cause.


>> [a.field2] = 1:3

??? Error using ==> colon
Too many output arguments.

The solution is here, to use deal function:
>> [a.field2] = deal(1,2,3)
a =
1x3 struct array with fields:
  field1
  field2
>> a.field2
ans =
   1

ans =
   2

ans =
   3

Just in case, make sure to use comma to separate values in right hand side otherwise whole values would be set to each struct.
>> [a.field2] = deal(1:3)
a =
1x3 struct array with fields:
  field1
  field2

>> a.field2
ans =
   1   2   3

ans =
   1   2   3

ans =
   1   2   3