如何在MATLAB中动态访问结构的字段的字段? [英] How can I dynamically access a field of a field of a structure in MATLAB?

查看:212
本文介绍了如何在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.

说我有一个结构toplevel,该结构是从MATLAB命令行中定义的,内容如下:

Say I have a structure toplevel, which I define from the MATLAB command line with the following:

midlevel.bottomlevel = 'foo';
toplevel.midlevel = midlevel;

我可以通过将字段名称作为字符串传递来访问midlevel结构,例如:

I can access the midlevel structure by passing the field name as a string, e.g.:

fieldnameToAccess = 'midlevel';
value = toplevel.(fieldnameToAccess);

但是我无法以相同的方式访问bottomlevel结构-以下是无效的语法:

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'

我可以编写一个函数,该函数可以在fieldnameToAccess中浏览一段时间,然后递归地迭代以获得所需的字段,但是我想知道是否存在使用MATLAB内置函数直接获取字段值的巧妙方法.

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.

推荐答案

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

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

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

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

这篇关于如何在MATLAB中动态访问结构的字段的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆