Reputation: 13
I'm trying to access a class property from within a method function. When I modify the property from the constructor, the setter is called and the property is changed. But when I modify the property from another method, the property reverts to the previous value, when the function is terminated, even though the setter is called again.
What is wrong with my code, please help me! Thanks
The code is below:
classdef random
properties
x
end
methods
function obj=random(obj)
obj.x = 2
obj.foo(1)
obj %output x:2, but it should be 1!
end
function foo(obj,A)
obj.x = A;
obj %output x:1
end
function obj = set.x(obj,newVal)
obj.x = newVal;
end
end
end
Upvotes: 1
Views: 305
Reputation: 241
Somebody correct me if I am wrong, but I assume the obj in foo is passed by value. So it does get updated within that function space but not returned. So what works is to have it return the object and catch that in the constructor. Try:
classdef random
properties
x
end
methods
function obj=random(obj)
obj.x = 2;
obj = obj.func1(4);
disp(obj.x);
end
function [obj] = func1(obj,A)
obj.x = A;
disp(obj.x);
end
function obj = set.x(obj,newVal)
obj.x = newVal;
end
end
end
Upvotes: 2