Hello,
I would like to programmatically reference different struct fields and I traditionally do that with the .() reference.
example_struct.(fieldname(i)) = some_data;
With my current project I would like to perform a similar reference, but the specific struct variable are of different depths. For example if I have the following struct
S.a.b.c = 1;S.a.b.d = 2;S.a.b.e = struct('f',[3 4],'g',5);S.h = 50
I would like to do the equivalent of the following code, but dynamically reference the sub structs.
S.a.b.c = some_val(1);S.a.b.e.f = some_val(2);S.h = some_val(3);
I attempted the following code and it does not work.
fields_names = {'a.b.c';'a.b.e.f';'h'};for i = 1:3 S.(field_names{i}) = some_val(i);end%I also tried
fields = {'a','b','c'};S = setfield(S,fields,some_val(1));
My question is how do I reference these fields dynamically and adjust their value inside the same loop. I could create the following function, but it is not very robust.
function S = fucntion_name(in_Struct,field_names,depth,value) switch depth %Other cases omitted
case 3 S = in_Struct.(field_names(1)).(field_names(2)).(field_names(3)) = value; endend
Is there another way? Is there a way to pass the values into setfield() similarly to how multiple function varargin inputs can be pass as a single struct input?
Best Answer