Accessing Dynamic Field References of Nested Structures
Show older comments
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)
Caspar Jespersen
on 28 Dec 2016
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
Gabor Bekes
on 17 Jul 2019
Edited: Gabor Bekes
on 17 Jul 2019
Please note that getfield will bite you if one of your fields is a struct array - it will silently return the first one.
Azzi Abdelmalek
on 26 Feb 2013
Edited: Azzi Abdelmalek
on 26 Feb 2013
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
Jonathan Currie
on 26 Feb 2013
Azzi Abdelmalek
on 26 Feb 2013
You can handle it, I gave a hint
Azzi Abdelmalek
on 26 Feb 2013
a.b.c.d=10
x=a
while isstruct(x)
s=char(fieldnames(x))
x=x.(s)
end
Categories
Find more on Structures in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!