MATLAB: Abbreviate acces to struct fields

dot indexingMATLABstructures

Hello everyone,
i often need to acces a struct field like
sturcture.firstLevel.secondLevel.thirdLevel = 1
Now my question is: Is there a way to abbreviate this long code? Something like defining a pointer.
For example:
sThird = pointer(sturcture.firstLevel.secondLevel.thirdLevel)
Whereas from now I could substitute
sThird
for
sturcture.firstLevel.secondLevel.thirdLevel
Is there a way to do this, so my code is to long?
Thank you for your time reading this.
Rafael

Best Answer

With structures, no it's not possible. Matlab does not support pointers/reference to variables. The workaround is to define a new variable, use that variable to do whatever you wanted to do, and then reassign that variable back to the structure
sThird = structure.firstLevel.secondLevel.thirdLevel;
%do something with sThird
structure.firstLevel.secondLevel.thirdLevel = sThird;
The only other way would be for the content of that thirdLevel field to be a handle class object that wrap whatever it is you store in there. In my opinion, this would be a waste of time just to offer shorter typing in the editor.
edit: forgot another option, which I also don't think is a good idea, use getfield and setfield:
field = {'firstlevel', 'secondlevel', 'thirdLevel'};
value = getfield(structure, field);
setfield(structure, field, someothervalue);