フィルターのクリア

How to change object's property in getter function of dependent variable ?

2 ビュー (過去 30 日間)
Atakan Zeybek
Atakan Zeybek 2020 年 8 月 23 日
編集済み: Matt J 2020 年 8 月 23 日
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
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
Matt J 2020 年 8 月 23 日
編集済み: Matt J 2020 年 8 月 23 日
You could switch to a regular method,
classdef Program
properties
prop = 200;
end
methods
function [val,obj] = depProp(obj)
val = obj.prop*rand;
if val>100
obj.prop = 100;
end
end
end
end

Matt J
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

カテゴリ

Help Center および File ExchangeSoftware Development Tools についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by