如何在 MATLAB 中动态访问结构体字段的字段?
我对访问一个字段的一般问题感兴趣,该字段可能埋藏在包含结构深处的任意数量的级别。下面是使用两个级别的具体示例。
假设我有一个结构体 toplevel
,我通过 MATLAB 命令行使用以下命令定义该结构体:
midlevel.bottomlevel = 'foo';
toplevel.midlevel = midlevel;
我可以通过将字段名称作为字符串传递来访问 midlevel
结构体,例如:
fieldnameToAccess = 'midlevel';
value = toplevel.(fieldnameToAccess);
但我无法以相同的方式访问 bottomlevel
结构 - 以下是无效语法:
fieldnameToAccess = 'midlevel.bottomlevel';
value = toplevel.(fieldnameToAccess); %# throws ??? Reference to non-existent field 'midlevel.bottomlevel'
我可以编写一个函数,通过 fieldnameToAccess
查找句点,然后递归迭代通过获取所需的字段,但我想知道是否有一些巧妙的方法可以使用 MATLAB 内置函数直接获取字段值。
I'm interested in the general problem of accessing a field which may be buried an arbitrary number of levels deep in a containing structure. A concrete example using two levels is below.
Say I have a structure toplevel
, which I define from the MATLAB command line with the following:
midlevel.bottomlevel = 'foo';
toplevel.midlevel = midlevel;
I can access the midlevel
structure by passing the field name as a string, e.g.:
fieldnameToAccess = 'midlevel';
value = toplevel.(fieldnameToAccess);
but I can't access the bottomlevel
structure the same way -- the following is not valid syntax:
fieldnameToAccess = 'midlevel.bottomlevel';
value = toplevel.(fieldnameToAccess); %# throws ??? Reference to non-existent field 'midlevel.bottomlevel'
I could write a function that looks through fieldnameToAccess
for periods and then recursively iterates through to get the desired field, but I am wondering if there's some clever way to use MATLAB built-ins to just get the field value directly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于您的示例,您必须将动态字段访问分为两个步骤,例如:
但是,有一种方法可以将此解决方案推广到具有任意数量的由句点分隔的子字段的字符串。您可以使用函数 TEXTSCAN 从字符串中提取字段名称,并函数 GETFIELD 一步执行递归字段访问:
You would have to split the dynamic field accessing into two steps for your example, such as:
However, there is a way you can generalize this solution for a string with an arbitrary number of subfields delimited by periods. You can use the function TEXTSCAN to extract the field names from the string and the function GETFIELD to perform the recursive field accessing in one step: