matlab: copy handle class as value class

463 Views Asked by At

Is it possible to make Matlab to call a copy method of my class TMyClass (which is a handle calss) when an object of this class is assigned to a variable. In other words, I want my handle class to behave as a value class when copying it:

obj = TMyClass(); %// has method "copy", which returns a deep copy of the object
%// Now, if I write this ...
obj_copy = obj;   
%// ... I want Matlab to do in fact this:
obj_copy = obj.copy; %// 

As I understood, there is no way to override the = operator in Matlab. Is there any other workaround to do so?

Thanks!

1

There are 1 best solutions below

0
On

If you have a value class, then obj_copy = obj will create a new copy of your object. For a handle class you always have to call a copy function yourself. I had the same issue already and would suggest you do a copy method as you proposed.

Depending on your design and what you want to do with it you could also go crazy and use fluent interfaces. In my case I had an object conaining data which returned filtered copies of itself in such a way:

obj = DataObject()
f1 = obj.getByType('pressure') % f1 ~= obj
f2 = f1.getByTemperature(@(x) x < 10) % using an anonymous function for filtering, also f2 ~= f1