Objects won't keep member variables

6 views (last 30 days)
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.

Accepted Answer

Titus Edelhofer
Titus Edelhofer on 15 Aug 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 Comments
Joseph
Joseph on 16 Feb 2015
Thank you!! This was frustrating me for awhile.

Sign in to comment.

More Answers (0)

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!