Updating a nested structure by a list of subfields

And one more episode of today "Fun with structs", this difficult one. I would like to dynamically create a nested structure over a specified list of subfields of arbitrary 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 I do that?


Of course, there is a solution to evil eval

, but I try to avoid evil.

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

      

+3


source to share


2 answers


You can use setfield

:

x = 42;
a.e = struct;
subfields = {'b','c','d'};

a = setfield(a, subfields{:}, x);

      



Which returns:

>> a.b.c.d

ans =

    42

      

+7


source


aa = x;
for i = numel(subfields):-1:2
    aa = struct(subfields{i}, aa);
end
a.(subfields{1}) = aa;

      



I hope the loop is not forbidden :)

+3


source







All Articles