Using a string shortcut for nested structure

11 次查看(过去 30 天)
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,

采纳的回答

Stephen23
Stephen23 2020-1-23
编辑:Stephen23 2020-1-23
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 个评论
Jos
Jos 2020-1-24
This is a nice, simple and eloquent way of reffering to nested structs. Many, many thanks!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by