Add Fields to an existing Structure
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (2)
Image Analyst
le 11 Juin 2022
0 votes
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 commentaires
Paul Mitchell
le 12 Juin 2022
Image Analyst
le 12 Juin 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:
Dror Liran
le 20 Déc 2023
Modifié(e) : Dror Liran
le 24 Déc 2023
What you are after is called dynamic field names, the matlab documatation is here: https://www.mathworks.com/help/matlab/matlab_prog/generate-field-names-from-variables.html
Anyway the way to do it is something like:
names = ["name1" "name2"];
a.fld1 = 1;
a.fld2 = "a";
a.(names(1)) = "whatever";
3 commentaires
Image Analyst
le 20 Déc 2023
Yes, but you'll forever be referring to a.((names(1)). You can never refer to a.name1 because that field name is in a variable that presumably might change from run to run. If you did, then that means the field name never varies, and if it never varies, why not just simply use a fixed field name and not worry about the parentheses? Like
a.var = "whatever";
Dror Liran
le 24 Déc 2023
I have tried it and it works for me on matlab 2023b
Stephen23
le 24 Déc 2023
"I have tried it and it works for me on matlab 2023b"
It should work in R2023b, dynamic fieldnames were added more than twenty years ago in R13:
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
