Hi,
I'd like to set a particular element of a structure array with a dynamic index to a field. So, for example, if fieldNames={'a' 'b' 'c'} and fieldValue=3, I want to set myStruct.a.b.c=3. I can hack together something that uses the eval function, say for example
str=['myStruct'];for ii=1:length(fieldnames)str=[str '.('''];str=[str fieldnames{ii}];str=[str ''')'];endeval([str '=' num2str(fieldValue)])
But is there a way to do this without using eval? I tried looking at setfield, but I can't get it to work. Running
x.a.b.c=3;fieldnames={'a' 'b' 'c'};getfield(x,fieldnames{:})
successfully returns 3, but running
setfield(x,fieldnames{:},5)
doesn't seem to do anything
Thanks
Brendan
Best Answer