Using a string shortcut for nested structure

12 visualizzazioni (ultimi 30 giorni)
Jos
Jos il 23 Gen 2020
Commentato: Jos il 24 Gen 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,

Risposta accettata

Stephen23
Stephen23 il 23 Gen 2020
Modificato: Stephen23 il 23 Gen 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 Commento
Jos
Jos il 24 Gen 2020
This is a nice, simple and eloquent way of reffering to nested structs. Many, many thanks!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by