MATLAB: How to modify private properties from inside a class

classhandleMATLABmethodobjectoopprivatevalue

Is it possible for me to modify a private property from inside a class?  When I call a public method to change a private property, the property appears to not actually be changed.  No errors are returned.

Best Answer

The default MATLAB class is a 'value' class.  If you call a method that changes a property of a 'value' class object, the operation will return a new object with the modification.  However the original object will remain unchanged unless reassigned.  To avoid this, inherit from the 'handle' class instead.  For more information about the difference between 'value' and handle classes, see the following documentation link:
https://www.mathworks.com/help/matlab/matlab_oop/comparing-handle-and-value-classes.html
The following code will give an example of using a public method to change a private property:
 
classdef CTester < handle
properties (Access = private)
expectedResult = [];
end
methods
function setExpectedResult(obj,In)
obj.expectedResult = In;
end
function y = getExpectedResult(obj)
y = obj.expectedResult;
end
end
end
Now try running to check that it works:
>> tester = CTester;
>> tester.setExpectedResult(2.87);
>> tester.getExpectedResult