Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: Assignment of objects in Matlab OOP
Replies: 1   Last Post: Feb 19, 2013 1:21 PM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View  
Steven Lord

Posts: 17,944
Registered: 12/7/04
Re: Assignment of objects in Matlab OOP
Posted: Feb 19, 2013 1:21 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply



"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




Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.