Matlab optimization: record data over iterations
<p><strong>Is it possible using Matlab for optimization to record data from one iteration to the next with a function m-file containing only the <a href="http://uk.mathworks.com/help/optim/ug/output-function.html" rel="nofollow">Output function</a>?</strong></p>

<p>The provided <a href="http://uk.mathworks.com/help/optim/ug/output-functions.html#brjhnpu" rel="nofollow">Example</a> shows that the optimization function needs be called from within a "runOptimization"-function where also the nested output function resides.</p>

<pre><code>function [history,searchdir] = runOptimization

% Set up shared variables with OUTFUN
history.x = [];
history.fval = [];
searchdir = [];

% call optimization
x0 = [-1 1];
options = optimoptions(@fmincon,'OutputFcn',@outfun,... 

% nested output function
function stop = outfun(x,optimValues,state)
    stop = false;
    switch state
    % ... store history and search directions over all iterations
</code></pre>

<p>Also <a href="https://uk.mathworks.com/help/matlab/math/output-functions.html#bsgpq6q-31" rel="nofollow">this site</a> claims that, if you want your output function to record data from one iteration to the next, you should write a single file that does the following:</p>

<ul>
<li>Contains the output function as a nested function.</li>
<li>Calls the optimization function.</li>
</ul>

<p>However, I was wondering if it is possible to create a m-file that contains just the output function and uses extra parameters <code>history</code> and <code>searchdir</code> as input.</p>

<p>I tried it with the following anonymous function approach, where the shared variables <code>history</code> and <code>searchdir</code> are declared "outside" in my main m-file (not global). And for the objective function and the output function I use seperate m-files.</p>

<pre><code>% main m-file
% Set up shared variables with OUTFUN
history.x = [];
history.fval = [];
searchdir = [];

outf = @(x,optimValues,state)outfun(x,optimValues,state,history,searchdir);

objective = @(x) objective_function(x,y,h);

x0 = [-1 1];
x = fmincon(objective,x0,[],[],[],[],[],[],[],options);
</code></pre>

<p>Though, every time the output function returns, the shared variables are empty again. Is there another solution instead of global variables, something like pass by reference instead of copies as arguments.</p>