I am writing a simple MATLAB class that has a few properties and a method. The constructor of the class initializes the properties with the default values. The method of the class gets an additional input after the class is constructed in order to update the class properties.
classdef classTest
properties
p1
p2
p3
p4
end
methods
function obj = classTest()
obj.p1 = 0;
obj.p2 = 0;
obj.p3 = [];
obj.p4 = '';
end
function obj = updateSomeProperties( obj, p1 )
obj.p1 = p1;
end
end
end
However, when I call the method of the class it does not update the properties.
>> b = classTest
b =
classTest with properties:
p1: 0
p2: 0
p3: []
p4: ''
>> b.updateSomeProperties(10)
ans =
classTest with properties:
p1: 10
p2: 0
p3: []
p4: ''
>> b % still used the default values.
b =
classTest with properties:
p1: 0
p2: 0
p3: []
p4: ''
I wanted to know why after calling the method of the class, b
is not updated although updateSomeProperties
updates the class object.
The issue is that your class is a value class which is passed (even to it's own methods) as a copy. This is the default behavior for MATLAB classes as this is what all fundamental MATLAB datatypes are. We can verify that this is the case by looking at the output of your call to updateSomeProperties()
. You will see that the returned result (shown as ans
) contains the modification that you expect but these changes are not present in your original object, b
. If you wanted to stick with a value class, you would need to return the new object from the method and re-assign the variable when calling the method.
b = classTest();
b = b.updateSomeProperties(10);
What you want is a handle class which is always passed by reference. This allows a method to operate on the same object rather than modifying a copy of the original object.
To do this, you will want to inherit from the built-in handle
class.
classdef classTest < handle
There is a detailed comparison of handle and value classes in the documentation.
As a side-note, rather than manually setting all default property values in the constructor, it is possible to simply specify these defaults within the properties
block itself.
properties
p1 = 0;
p2 = 0;
p3 = [];
p4 = '';
end
Your class needs to inherit from the handle superclass. Try:
classdef classTest < handle
properties
p1
p2
p3
p4
end
methods
function obj = classTest()
obj.p1 = 0;
obj.p2 = 0;
obj.p3 = [];
obj.p4 = '';
end
function obj = updateSomeProperties( obj, p1 )
obj.p1 = p1;
end
end
end
This will give,
>> b = classTest
b =
classTest with properties:
p1: 0
p2: 0
p3: []
p4: ''
>> b.updateSomeProperties(10)
ans =
classTest with properties:
p1: 10
p2: 0
p3: []
p4: ''
>> b
b =
classTest with properties:
p1: 10
p2: 0
p3: []
p4: ''