Azzera filtri
Azzera filtri

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

2 visualizzazioni (ultimi 30 giorni)
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 Commento
Matt J
Matt J il 23 Ago 2020
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;

Accedi per commentare.

Risposte (2)

Matt J
Matt J il 23 Ago 2020
Modificato: Matt J il 23 Ago 2020
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 il 23 Ago 2020
Modificato: Matt J il 23 Ago 2020
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

Categorie

Scopri di più su Software Development Tools in Help Center e File Exchange

Prodotti


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by