如何在 MATLAB 中动态访问结构体字段的字段?

发布于 2024-09-24 04:29:00 字数 721 浏览 1 评论 0原文

我对访问一个字段的一般问题感兴趣,该字段可能埋藏在包含结构深处的任意数量的级别。下面是使用两个级别的具体示例。

假设我有一个结构体 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫瑾少女 2024-10-01 04:29:00

对于您的示例,您必须将动态字段访问分为两个步骤,例如:

>> field1 = 'midlevel';
>> field2 = 'bottomlevel';
>> value = toplevel.(field1).(field2)

value =

foo

但是,有一种方法可以将此解决方案推广到具有任意数量的由句点分隔的子字段的字符串。您可以使用函数 TEXTSCAN 从字符串中提取字段名称,并函数 GETFIELD 一步执行递归字段访问:

>> fieldnameToAccess = 'midlevel.bottomlevel';
>> fields = textscan(fieldnameToAccess,'%s','Delimiter','.');
>> value = getfield(toplevel,fields{1}{:})

value =

foo

You would have to split the dynamic field accessing into two steps for your example, such as:

>> field1 = 'midlevel';
>> field2 = 'bottomlevel';
>> value = toplevel.(field1).(field2)

value =

foo

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:

>> fieldnameToAccess = 'midlevel.bottomlevel';
>> fields = textscan(fieldnameToAccess,'%s','Delimiter','.');
>> value = getfield(toplevel,fields{1}{:})

value =

foo
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文