Add Fields to an existing Structure

11 views (last 30 days)
Paul Mitchell
Paul Mitchell on 11 Jun 2022
Commented: Image Analyst on 12 Jun 2022
Hi,
I have structure, for example
S.Level0=0
I have a field structure I want to add to S namely
S.Level1.SubLevel0.SubLevel1.SubLevel2.Text = '1234';
where i have the above fields defined in a cell array
f = {'SubLevel0','SubLevel1','SubLevel2','Text'}
and the string cvar='1234' being the required value
is there an elegant way to produce
S.Level1.SubLevel0.SubLevel1.SubLevel2.Text='1234'
using f & cvar ?
Thank You

Accepted Answer

Paul
Paul on 11 Jun 2022
S.Level0=0;
f = {'SubLevel0','SubLevel1','SubLevel2','Text'};
cvar = '1234';
S = setfield(S,'Level1',f{:},cvar);
S.Level0
ans = 0
S.Level1.SubLevel0.SubLevel1.SubLevel2.Text
ans = '1234'
  4 Comments
Paul Mitchell
Paul Mitchell on 12 Jun 2022
Thank you very much for spending time to provide me with the solution. I thought I had tried everything possible !! Clearly I did not - Regards Paul

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 11 Jun 2022
Having field names that are unknown in advance, and their names are only determined by getting their name from a cell array variable sounds like a bad idea. It's probably one of the worst and most common ideas and it comes up every week.
However it is possible to do bad things in MATLAB and the FAQ will show you how to do it and explain why it's bad.
I'm sure Stephen will also chime in with additional reasons why you really don't want to do this even though you think you do.
  2 Comments
Image Analyst
Image Analyst on 12 Jun 2022
The solution you accepted will do what you want but as you can see, to get this unknown field name you have to do some pretty cryptic stuff that makes the code almost unmaintainable. Would be better to use fixed and known names rather than dynamically varying names, as I hope someday you realize. But good luck with it. You might also like to read the FAQ:
And Stephen's tutorial:

Sign in to comment.

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!