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

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

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

카테고리

도움말 센터File Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2020년 8월 23일

편집:

2020년 8월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by