Objects won't keep member variables

8 visualizaciones (últimos 30 días)
Tilman
Tilman el 15 de Ag. de 2012
Comentada: Jixiong Su el 2 de Nov. de 2023
Hello. I have a container class that holds an array 'arr' to store instances of the item class. The item class has to member variables called variable1 and variable2.
classdef container
properties
arr;
end
methods
function this = container(n)
this.arr = item.empty(n,0);
for i = 1:n
this.arr(i) = item(4); %set value1 to 4
end
end
end
end
%------------------------------------------------------
classdef item
properties
value1;
value2;
end
methods
function this = item(v)
this.value1 = v;
end
function setValue2(this, v)
this.value2 = v;
end
end
end
%------------------------------------------------------
clear all;
c = container(2);%container able to hold 2 item objects
c.arr(1).setValue2(9); %set value2 of first item to 9
c.arr(1).value1 %display value1 and value2 of first item
c.arr(1).value2
Wenn I run the last part I get this result:
ans = 4
ans = []
So value1 is set correctly in the Constructor, whereas value2 is set via a seperate function called setValue2. When I debug I can see that setValue2(9) sets value2 to 9 but when I leave the function value2 becomes an empty double again.
What am I doing wrong? Why doesnt Matlab keep the value? Do I use item.empty() the wrongt way? I didn't find any other option to declare an empty array of type 'item'.
Tanks you for every answer.

Respuesta aceptada

Titus Edelhofer
Titus Edelhofer el 15 de Ag. de 2012
Hi,
the way you write the code is correct, if you have "handle-semantics". For value semantics you have to return the changed object (think of the methods as usual matlab functions), so:
function this = setValue2(this, v)
this.value2 = v;
end
and call like
c.arr(1) = c.arr(1).setValue2(9);
If you don't like this, change your class to be a "handle" class by changing only the definition:
classdef item < handle
Then you c.arr(1) is not the object itself but a reference to the object.
Titus
  3 comentarios
Joseph
Joseph el 16 de Feb. de 2015
Thank you!! This was frustrating me for awhile.
Jixiong Su
Jixiong Su el 2 de Nov. de 2023
Thanks a lot!

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.

Community Treasure Hunt

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

Start Hunting!

Translated by