MATLAB: Using Set Field for multiple depths

dynamic structure allocationgetfieldsetfield

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 ''')'];
end
eval([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

You will not be able to do this using setfield() or getfield(), not in any useful way.
You should refer to subsref() and subsassgn(). They are a bit clumsy to use, but they can handle the task.