title: Why does the save command fail when called from within a listener callback function?
body: <p>I'm trying to call MATLAB's <strong>save</strong> function from inside a listener callback function to save some computed results to disk in a .mat file. My program has a GUI and is organized using a MVC pattern. When the user presses a button in the GUI, the button's callback for the button press calls a method on the Model class. That method in the Model class in turn issues an event notification:</p>
  <pre><code>notify(this, 'EstimateModelParametersRequest');
  </code></pre>
  <p>Back in the View, a listener was registered for that event when the GUI was first initialized:</p>
  <pre><code>addlistener(m, 'EstimateModelParametersRequest', ...
          @(o,e) OnEstimateModelParametersRequest(handles, e.Source));
  </code></pre>
  <p>So, when the use clicks the button, what ultimately happens is that a function in the View is listening for and handles the event:</p>
  <pre><code>function OnEstimateModelParametersRequest(handles, model)
       % There's some code here that calls methods of the Model class to compute results and then plots those results
  
       % After plotting the results, we want to save them to disk
       [filename, pathname] = uiputfile({'*.mat'}, 'File to save results in', 'results.mat');
       save(fullfile(pathname, filename), 'results', '-mat');
  end
  </code></pre>
  <p>The problem that I keep running into is that the call to <strong>save</strong> routinely fails, giving the following error:</p>
  <pre><code>Warning: Error occurred while executing the listener callback for event
  EstimateModelParametersRequest defined for class Model:
  Error using save
  Error closing file C:\myfilepath\myresults.mat.
  The file may be corrupt.
  </code></pre>
  <p>My best guess as to what might be happening is that perhaps the function call to <strong>save</strong> is returning to the calling function before it has finished writing all of the data to disk, the calling function returns immediately after the call to <strong>save</strong> thus triggering deallocation of the local variables that were used within the <strong>OnEstimateModelParametersRequest</strong> function. Because there's a lot of data to be written to disk, ultimately deallocation and garbage collection of the local variable <strong>results</strong> happens before the save operation completes.</p>
  <p>If that is indeed what is happening, then it would seem that the solution would be to somehow force <strong>save</strong> to flush the write cache or some such thing in order to ensure the data is persisted before the <strong>OnEstimateModelParametersRequest</strong> function exits. Is that indeed what's going on and, if so, how can I force the <strong>save</strong> operation to complete?</p>