Update nested structure by list of subfields

Viewed 91

And another episode of today's "Fun with structs", this one is a tough one. I'd like to create a nested structure dynamically by a given list of subfields of arbitary length, like in the following example:

x = 42;
a.e = struct;
subfields = {'b','c','d'}; %// arbitary length!

%// desired result
a.b.c.d = x;

How can that be done?


Of course there is an evil eval solution, but I try to avoid to be evil.

evalexp = ['a' cellfun(@(s) ['.' s], subfields, 'uni',0)];
evalexp = [evalexp{:}];
eval( [evalexp '= x'])
2 Answers
Related