MATLAB: How to write ‘setter’ methods for properties with unknown names

MATLABooprecursion

The following class cannot be initialized, as any call to the constructor gives the error:
>> MyClass('a',2)
Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the limit. Be aware that exceeding your available
stack space can crash MATLAB and/or your computer.
Error in MyClass/MyClass/@(o,p)setProp(o,propname,p)
 
classdef MyClass < dynamicprops
methods
function obj = MyClass(propname, val)
P = obj.addprop(propname);
P.SetMethod = @(o,p)setProp(o,propname,p);
obj.(propname) = val;
end
function setProp(obj, propname, val)
% do other stuff, like evaluating if val is legitimate
obj.(propname) = val;
end
end
end
Why is this, and what is the best way to write custom 'set' methods for dynamic properties with unknown names?

Best Answer

The infinite recursion is caused by the line 'obj.(propname) = val;' in setProp. This calls the SetMethod for the property 'propname'. When setting the value of a property, MATLAB checks to see if you are currently in the SetMethod for that property in order to avoid infinite recursion. However, since your SetMethod is an anonymous function which calls setProp (and not setProp itself), this assignment is not inside the SetMethod, and the assignment calls the anonymous function.
To avoid this issue, you may use a nested function as shown below:
% start of file MyClass2.m
classdef MyClass2 < dynamicprops
methods
function obj = MyClass2(propname, val)
P = obj.addprop(propname);
P.SetMethod = propSetFcn(obj, propname);
obj.(propname) = val;
end
end
end
function f = propSetFcn(obj, propname)
function setProp(obj, val)
% do other stuff
obj.(propname) = val;
end
f = @setProp;
end
% end of file MyClass2.m