MATLAB: Does the property of the class object not getting changed via a method

changeclassfunctiongettingMATLABmethodmodifiednotoopproperty

I have a class, with properties and methods. I am using a method in the class to change a particular property, but the property is not getting changed. Why is this?
See the example here : 
 
classdef tempClass
properties
Value = 1;
end
methods
function changeValue(obj)
obj.Value = 2;
end
end
end
Now, I execute : 
 
>> a = tempClass;
>> a.changeValue;
>> a.Value
ans =
1
Why is this happening?  

Best Answer

  • The way this class is defined, it is a value class. For value classes, functions must return the modified value.
    If you do not want to return the modified object in the function, then you can make this class a handle class as follows : 
     
    classdef tempClass < handle
    %Now the class inherits 'handle', so it is a handle class
    properties
    Value = 1;
    end
    methods
    function changeValue(obj)
    obj.Value = 2;
    end
    end
    end
    Now the class and the function work are expected.