Problem with object oriented progamming - codepedent variables

1 view (last 30 days)
Hello guys, I've got a problem with a class of the object that I want to create. I want it to work in that way: Once I change the parameter 'A', I want second parameter 'B' to change automatically, and once I change the second parameter 'B' I want the first parameter 'A' change adequatly:
classdef ModelBrick
properties
A=1
B=1
end
methods
function a= set.A(obj)
obj.A=a*obj.B;
end
function b= set.B(obj)
obj.B=obj.A/b;
end
end
end
Obviously it doesn't work. It enters into infinit loop. Do you have any idea how to deal with this problem? Thank you in advance.

Accepted Answer

Teodor
Teodor on 15 Apr 2014
Thanks a lot Matt for your time. I found the answer thank to you.
classdef ModelBrick
properties
B=1
C=20
end
properties(Dependent = true)
A=1
end % end of dependent properties
methods
function obj= set.A(obj,a)
obj.B=a/obj.C
end
function a= get.A(obj)
a=obj.B*obj.C;
end
end
end

More Answers (1)

Matt J
Matt J on 14 Apr 2014
No, the code you've shown won't enter an infinite loop. It will generate an error because the parameter "a" in
obj.A=a*obj.B;
is never passed to set.A() as an input argument and similarly for the parameter "b". Also, set methods need to return an obj of the class instead of numeric scalars like a and b.
However, the solution to your problem is probably to make either A or B a Dependent Property.
  2 Comments
Matt J
Matt J on 14 Apr 2014
Teodor Commented:
Sorry, you are right, but if I put that way:
classdef ModelBrick
properties
A=1
B=1
end
methods
function obj= set.A(obj,a)
obj.A=a*obj.B;
end
function obj= set.B(obj,b)
obj.B=obj.A/b;
end
end
end
It doesn't work neither.
Matt J
Matt J on 14 Apr 2014
Works fine for me, i.e., I get no error messages. The Code Analyzer does warn you not to refer to multiple properties in the set() methods and you should take that seriously. That's why I referred you earlier to the documentation on Dependent Properties

Sign in to comment.

Categories

Find more on Software Development Tools in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!