How can I dynamically access a field of a field of a structure in MATLAB?

余生颓废 提交于 2019-12-21 16:57:33

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/3753642/how-can-i-dynamically-access-a-field-of-a-field-of-a-structure-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!