Using a string shortcut for nested structure

12 vues (au cours des 30 derniers jours)
Jos
Jos le 23 Jan 2020
Commenté : Jos le 24 Jan 2020
Hi all,
I tried using the search function but to no avail. Hopefully you can help me with this one.
Suppose I have a structure called 'tmp':
tmp = struct();
tmp.ahoy.matey = 'hello';
Would it be possible to create a sort of an 'alias' or shortcut using a string to get to 'hello' in a direct way, and also reassign it? I tried:
blah = 'ahoy.matey';
tmp.(blah) = 'hi';
But that gets me an error.
Invalid field name: 'ahoy.matey'.
Sure, I can evaluate it:
eval(['tmp.' blah])
ans =
'hello'
But I cannot really change 'hello' into something different.
Is there a way to do this?
Thank you!
Best regards,

Réponse acceptée

Stephen23
Stephen23 le 23 Jan 2020
Modifié(e) : Stephen23 le 23 Jan 2020
For accessing a field of one specific structure (which can be nested) you should use dynamic fieldnames:
For accessing multiple arbitrary fields of arbitrarily nested structures the most robust way is to use setfield and getfield, for which you will need to split the string into the separate field names (because each field belongs to a different structure, they cannot be provided as one string) which can be provided as a comma-separated list, for example:
>> tmp = struct();
>> tmp.ahoy.matey = 'hello';
>> str = 'ahoy.matey';
>> spl = regexp(str,'\.','split');
>> getfield(tmp,spl{:})
ans = hello
>> tmp = setfield(tmp,spl{:},'world');
>> getfield(tmp,spl{:})
ans = world
See also:
TIP: even better than passing around that string would be to just pass the cell array spl.
  1 commentaire
Jos
Jos le 24 Jan 2020
This is a nice, simple and eloquent way of reffering to nested structs. Many, many thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by