Class Property assignment and read

8 views (last 30 days)
if true
% code
endI am trying to use classes in MATLAB and I’m tripping over a property assignment in a class. I am trying to assign a value to a property in one function and read this property back in another function.
When I go to read the value back the value I assigned it no longer is applied to the property. I am not sure what I am doing wrong? Test class
classdef Class_Test
%-------------------------------
% Properties
%-------------------------------
properties (Access = private)
X
end
%-------------------------------
% Methods
%-------------------------------
methods
function set_X(this)
this.X = 1;
this.X
end
function read_X(this)
this.X
end
end
end
Output of Object:
>> TC = Class_Test;
>> TC.set_X
ans =
1
>> TC.read_X
ans =
[]
What I expected was:
>> TC.read_X
ans =
1

Accepted Answer

Geoff Hayes
Geoff Hayes on 7 Mar 2015
Matt - I think the problem is how you have defined your class. From Comparing Handle and Value Classes
MATLAB associates objects of value classes with the variables to which you assign them. When you copy a value object, MATLAB also copies the data contained by the object. The new object is independent of changes to the original object.
Objects of handle classes use a handle to reference objects of the class. A handle is a variable that identifies an instance of a class. When you copy a handle object, MATLAB copies the handle, but not the data stored in the object properties. The copy refers to the same data as the original handle. If you change a property value on the original object, the copied object reflects the same change.
So there are two types of classes: value and handle. By default, your class is of type value which is fine, but it requires more code to get the behaviour that you expect. Try deriving your class from handle as
classdef Class_Test < handle
and then re-run your example and it should work fine. If you want to get your class to work as a value class, then you would need to do something like the following to your set method
function [this] = set_X(this)
this.X = 1;
this.X
end
and then re-assign the output from this assignment as
TC = TC.set_X;
Much easier/cleaner to derive your class from handle.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!