Class properties are being reinitialized each time I call a method

Hi, class properties are being reinitialized each time I call a method. the result of the multiplication is always 15. Could you please tell me where is the error? I don't want to use any argument in the constructor method.
classdef Multi
properties
x = 0;
y = 0;
end
methods
function obj = Multi()
obj.x = 5;
obj.y = 3;
end
function obj = X (obj, x)
obj.x = x;
end
function obj = Y (obj, y)
obj.y = y;
end
function obj = Mul (obj)
disp (obj.x * obj.y);
end
end
end

 Accepted Answer

You've shown the class definition, but not your test code. So, the problem appears to be entirely in your imagination:
>> obj=obj.X(20);
>> obj=obj.Y(10);
>> obj.Mul;
200
However, I suspect that you neglected to assign the output of obj.X() and obj.Y() as above. If you don't want to have to do that, you might consider making this a handle class.

7 Comments

Thank you! Yes, you are right. I neglected to assign the output. Could you tell me why should I have to assign one?
I would recommend you read the topics under Characteristics of Handle and Value Classes in the documentation that Matt has linked, particularly the first one which should explain why you need to assign the output.
Matlab distinguishes between value classes and handle classes. You have defined a value class.
Value class methods will not modify objects in the workspace from which they are called. Changes to the object will be local to the workspace of the method. Handle classes will do what you want, so as I mentioned before, you may want to consider making Mult a handle class instead. Just change the first line as follows
classdef Multi < handle
However, with handle classes, you can only create new objects by calling the constructor. Something like the following will not work,
obj=Multi;
objnew=obj; objnew.x=7;
which you can test by doing,
>> obj.x
ans =
7
>> objnew.x
ans =
7
Thank you all for the hello. Could you please explain how this class is different from the other one.
classdef Mul_class
properties %
x;
y;
end
methods
function obj = Mul_class(x,y)
obj.x = x;
obj.y = y;
end
function sum = Mul (obj)
sum = obj.x * obj.y;
end
function displ (obj)
disp (obj.x * obj.y);
end
end
end
The main difference I see is that your constructor must now be given input arguments x,y.
I get your point, thank you. What I have noticed is that, I have to assign an output for the "Sum" method of the first code while I can display the result of the second code by calling the "view" method without assigning an output. Can you provide an easy to understand tutorial for beginners please?

Sign in to comment.

More Answers (0)

Categories

Find more on Phased Array System Toolbox in Help Center and File Exchange

Asked:

on 5 Sep 2018

Commented:

on 5 Sep 2018

Community Treasure Hunt

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

Start Hunting!