Accessing Dynamic Field References of Nested Structures

Hi - I want to be able to dynamically get and set fields of a structure, but a structure with nested fields, such as:
param.limits.iterations = 100
So, I know I can do the following:
param.limits.('iterations') = 100
But I would like to do this:
param.('limits.iterations') = 100
As I have complex parameter structure (for the Cplex MATLAB interface), and wish to be able to enter user selected parameters into it.
Any ideas appreciated! I have tried setfield and subsasgn, but due to the way the Cplex object is created the parameter structure (class property) is copied everytime I do something like:
cp.param = setfield(cp.param,...)
meaning it is way too slow with so many fields to access! Note the level of nesting is variable - there may be 2 levels, or 6.

Answers (2)

There is a solution, even though it's a bit late now :-)
Input:
a = struct;
a.b.c.d = 10;
dynamicPath = {'b' 'c'};
disp(getfield(a, dynamicPath{:}));
Output:
d: 10
Note: MATLAB warns against using this type of calling, but I haven't been able to find other solutions.

1 Comment

Please note that getfield will bite you if one of your fields is a struct array - it will silently return the first one.

Sign in to comment.

You can use getfield
a.b.c=10
out=getfield(a.('b'),'c')
%or
a.b.c.d=10
x1=a.('b');
x2=x1.('c');
x3=x2.('d')

3 Comments

If the level of nesting is variable (which in my problem it is), then I don't believe your solution will work.
You can handle it, I gave a hint
a.b.c.d=10
x=a
while isstruct(x)
s=char(fieldnames(x))
x=x.(s)
end

Sign in to comment.

Categories

Products

Asked:

on 26 Feb 2013

Edited:

on 17 Jul 2019

Community Treasure Hunt

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

Start Hunting!