MATLAB Answers

I have a structure within a structure (a nested structure), and am trying to add a field to that structure, what should I write?

4 views (last 30 days)
Guy Nir
Guy Nir on 23 Mar 2017
Commented: Guy Nir on 23 Mar 2017
Doesn't work...


Sign in to comment.

Answers (1)

Fabian Schadt
Fabian Schadt on 23 Mar 2017
Edited: Stephen Cobeldick on 23 Mar 2017
Hi Guy Nir,
actually there should be no problem.
s.Field.FieldName = zeros(1,1);
works ;-)
However, if you state your nested struct with brackets ->
then you access with (FieldName) a variable in your workspace. If this does not exist, you receive an error.
If brackets, then it would be like this:
FieldName = [];
s.Field.(FieldName) = zeros(1,1);
Hope I could help!


Show 2 older comments
James Tursa
James Tursa on 23 Mar 2017
Works for me:
>> clear all
>> FieldName='valid'
FieldName =
>> s.Field.(FieldName) = zeros(1,3)
s =
Field: [1x1 struct]
>> s.Field.valid
ans =
0 0 0
You should double check what the variable s really is. Are you sure it isn't maybe a cell array that contains structures, or something like that?
Guy Nir
Guy Nir on 23 Mar 2017
Thanks. It seems that because I had a 2X1 structure within a structure, it was a bit more complicated. but i got it done thanks to all of you!

Sign in to comment.

Sign in to answer this question.