title: MATLAB Lazy Evaluation in Dependent Property
body: <p>I have a class with a few properties that are dependent, but that I'd really like to calculate only once. </p>
  
  <p>I've just about concluded that using lazy evaluation on a dependent class property in MATLAB is either impossible or a bad idea. The original plan was to have a private logical flag for each (public) property that needs updating and to have the constructor set it to true. Then when the property accessor was called, it would check that flag and calculate the value and store it (in another private property) only if required. If the flag were false, it would simply return a copy of the cached value.</p>
  
  <p>I believe the difficulty lies in a constraint on property accessors, that is, that they leave other unrelated properties alone. In other words, a get.property(self) method can't change the state of the self object. Interestingly, this fails silently in my current class. (I.e., the neither the update flag nor the cached calculation results get set in the get. method, so the expensive calculation is run every time).</p>
  
  <p>My suspicion is that changing the lazy property from a public dependent property to a method with public GetAccess but private SetAccess would work. However, I don't like having to spoof the property convention in this way. I wish there were just a "lazy" property attribute that could do all this for me.</p>
  
  <p>Am I missing something obvious? Are accessor methods for dependent class properties in MATLAB forbidden to change the class instance's state? If so, is defining what amounts to an accessor with a private side effect the least evil way of getting the behavior I want?</p>
  
  <p>Edit: here's a test class...</p>
  
  <pre><code>classdef LazyTest
    properties(Access = public)
      % num to take factorial of
      factoriand
    end
  
    properties(Access = public, Dependent)
      factorial
    end
  
    properties(Access = private)
      % logical flag
      do_update_factorial
      % old result
      cached_factorial
    end
  
    methods
      function self = LazyTest(factoriand)
        self.factoriand = factoriand;
        self.do_update_factorial = true;
      end
    end
  
    methods
      function result = get.factorial(self)
        if self.do_update_factorial
          self.cached_factorial = factorial(self.factoriand);
          % pretend this is expensive
          pause(0.5)
          self.do_update_factorial = false
        end
        result = self.cached_factorial;
      end
    end
  end
  </code></pre>
  
  <p>Run it with </p>
  
  <pre><code>close all; clear classes; clc
  
  t = LazyTest(3)
  t.factorial
  
  for num = 1:10
    tic
    t.factoriand = num
    t.factorial
    toc
  end
  </code></pre>
  
  <p>After inheriting from <code>handle</code> the time drops substantially.</p>