Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
Drexel University or The Math Forum.
|
|
|
|
Re: Assignment of objects in Matlab OOP
Posted:
Feb 19, 2013 1:21 PM
|
|
"JayTee " <d.tran@neu.edu> wrote in message news:kg0dhr$ar3$1@newscl01ah.mathworks.com... > I have an object A of a user-defined class. > A.x = 1; A.y = 2; > > Now when I let B = A, any operation on B will also change the > corresponding properties in A. So if I set B.x = 5, I get A.x = 5 as well.
That only happens if your class is a handle class, and that is the expected and desired behavior for handle classes.
http://www.mathworks.com/help/matlab/matlab_oop/comparing-handle-and-value-classes.html
> Is there a way to overcome this? I would want to replicate some objects > and then make modification to the new object's properties.
There are a couple approaches. The first, and probably simplest, is to make your class a value class (NOT a handle class) if you want value semantics. To do this, don't subclass handle.
The second approach is to make your handle class subclass from matlab.mixin.Copyable:
http://www.mathworks.com/help/matlab/ref/matlab.mixin.copyableclass.html
If for some reason you need your object to be a handle and can't subclass from matlab.mixin.Copyable you could always write your own copy or "clone" method that decouples the original object and its copy.
-- Steve Lord slord@mathworks.com To contact Technical Support use the Contact Us link on http://www.mathworks.com
|
|
|
|