Writing a subclass of dynamicprops
allows to me to add properties dynamically to an object:
addprop(obj, \'new_prop\')
This is gre
My experience with Matlab has been so far, that once I create an instance of a class, adding new methods is not possible. That is very cumbersome, because my object may contain a lot of data, which I'll have to re-load everytime that I want to add a new method (because I have to do
clear classes
).
It's worth noting for present-day readers of this question that this is no longer true. As of MATLAB R2014b MATLAB updates class definitions at the moment you save them, and the behaviour of existing class instances automatically updates accordingly. In the case of adding new methods, this is uncomplicated: the new method simply becomes available to call on class instances even if they were created before the method was added to the class.
The solutions given for choosing set/get methods for dynamic properties still apply.
There are still cases where you might want to add methods to an instance dynamically and the method doesn't constitute a property set/get method. I think the only answer in this case is to assign a function handle as the value to a dynamic property. This doesn't create a bona fide method, but will allow you to call it in the same way you would a method call:
addprop(obj, 'new_method');
obj.new_method = @(varargin) my_method(obj,varargin{:});
Calls to obj.new_method(args)
are thus passed to my_method
; however this only works with a scalar obj
; an array of instances will have separate values for the new_method
property so obj.new_method
no longer resolves to a single function handle that can be called if obj
is an array.