In a class, I have a dependent property that's expensive to calculate. It only depends on one other property, call it "value" in the class, so I'm trying to prevent it from re-calculating unless value changes.
The snippet below works, but it shows a warning about setting the property value for lazy in the set method for value. Is there a better way to do this?
classdef MyClass < handle
properties value; end
properties (Dependent) output; end
properties (Access = private) lazy = false; cachedOutput; end
methods function obj = MyClass(value) obj.value = value; end
function set.value(obj, value) obj.lazy = false; % warning here obj.value = value; end
function res = get.output(obj) if obj.lazy res = obj.cachedOutput; else res = expensive_function(obj.value); obj.cachedOutput = res; obj.lazy = true; end end end
function res = expensive_function(value) res = value + 1; end
No products are associated with this question.
I've seen a recommendation to use persistent variables in expensive_function
function res = expensive_function(value) persistent old_value old_res if not( isempty( old_value ) ) && value == old_value res = old_res; else res = value + 1; old_res = res; old_value = value; end end
whether it is better I don't know.
Play games and win prizes!Learn more