Using a string shortcut for nested structure

8 views (last 30 days)
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,

Accepted Answer

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

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!