How to change object's property in getter function of dependent variable ?
3 次查看(过去 30 天)
显示 更早的评论
Hello everyone,
Let's say we have a class which has "prop" as property and "depProp" is "Dependent" property. Moreover, it will have getter function to calculate "depProp". The class definition would be like :
classdef Program
properties
prop = 200;
end
properties (Dependent)
depProp
end
methods
function val = get.depProp(obj)
val = prop*rand;
if val>100
obj.prop = 100; % gives an error
end
end
end
end
However, MATLAB gives an error because get.depProp function does not return "obj" as output so it cannot change the property of object. I know why it is happenning (it is value class and the object must be returned). I do not want to switch to handle class. So how can I change the object's property in the getter function of dependent variable. Inefficient solutions are also welcome.
Thank you in advance,
1 个评论
Matt J
2020-8-23
However, MATLAB gives an error because get.depProp function does not return "obj" as output so it cannot change the property of object.
Matlab wouldn't give you an error message because of that. More likely, you are getting an error message because this line,
val = prop*rand;
should be,
val = obj.prop*rand;
回答(2 个)
Matt J
2020-8-23
编辑:Matt J
2020-8-23
Another solution (far less recommendable, IMO) would be to hold the property data in a handle object of a different class. This would avoid turning Program into a handle class of its own.
classdef myclass<handle
properties
data = 200;
end
end
classdef Program
properties (Hidden,Access=private)
prop_ = myclass;
end
properties (Dependent)
prop
depProp
end
methods
function val=get.prop(obj)
val=obj.prop_.data;
end
function obj=set.prop(obj,val)
obj.prop_.data=val;
end
function val = get.depProp(obj)
val = obj.prop*rand;
if val>100
obj.prop = 100;
end
end
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!