Class property automatically propagated to old class instances

6 visualizaciones (últimos 30 días)
Dear matlab user,
I struggle with the following problem I have with my own definition for a class I use. I will illustrate the problem by means of an example. Say I define the following class:
classdef exampleClass
properties
exampleProp double {mustBeFinite(exampleProp)}
end
methods
function obj = exampleClass(exampleProp)
arguments
exampleProp = []
end
obj.exampleProp = exampleProp;
end
end
end
Now I initiate a class instance as follows:
Exmp = exampleClass(1);
I have the following issue when I copy the object.
Exmp1 = exmp;
Exmp2 = exmp;
Exmp1.exampleProp = 5;
What I would like to happen is that Exmp1 is updated and Expm,Expm2 are unchanged. However all objects now have that the exampleProp property is changed to 5. How do assure that I can change a property value without it being propagated to other class instances?
Thanks you very much!

Respuesta aceptada

per isakson
per isakson el 18 de En. de 2022
Editada: per isakson el 18 de En. de 2022
Your exampleClass is a value class. However, the behavior you describe is more like that of a handle class. See the examples below. (To run the code I need to attach the classdef-files rather than including them in this text.)
%% value class
v = exampleClass(1);
v1 = v
v1 =
exampleClass with properties: exampleProp: 1
v2 = v
v2 =
exampleClass with properties: exampleProp: 1
v1.exampleProp = 5
v1 =
exampleClass with properties: exampleProp: 5
v
v =
exampleClass with properties: exampleProp: 1
v2
v2 =
exampleClass with properties: exampleProp: 1
%% handle class
h = exampleClass_handle(1);
h1 = h
h1 =
exampleClass_handle with properties: exampleProp: 1
h2 = h
h2 =
exampleClass_handle with properties: exampleProp: 1
h1.exampleProp = 5
h1 =
exampleClass_handle with properties: exampleProp: 5
h
h =
exampleClass_handle with properties: exampleProp: 5
h2
h2 =
exampleClass_handle with properties: exampleProp: 5
  1 comentario
Luuk Spin
Luuk Spin el 18 de En. de 2022
Thanks a lot! Indeed the class inherited properties from a superclass that inherited the handle class. I changed the superclass and now it works :)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by