Problem with object oriented progamming - codepedent variables

1 次查看(过去 30 天)
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.

采纳的回答

Teodor
Teodor 2014-4-15
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

更多回答(1 个)

Matt J
Matt J 2014-4-14
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 个评论
Matt J
Matt J 2014-4-14
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 2014-4-14
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

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by