MATLAB: How to add variables to the Plot Fcn

addfminconfminsearchMATLABoptimsetoptionsplotfcnplotfcnsvariable

I created a custom Plot Function for 'fminsearch':
opts = optimset('Display','iter','TolFun',1e-5,'MaxIter',100,'PlotFcns',@outf);
[v1, fval] = fminsearch(funtol,v1,opts);
function stop = outf(x, optimValues, state)
...<Plot some stuff>...
end
How can I add some variables to the Plot Function? For example:
function stop = outf(x, optimValues, state, var1, var2)
I don't know how to call it then in 'optimset' properly, because, it seems, there are no additional varibles allowed:
opts = optimset('PlotFcns',@outf<Don't know what to write here>);

Best Answer

One solution is to write an anonymous function and define the extra values prior to creating the anonymous function. Those extra values will then be stored in that function until it's deleted or overwritten. Example:
% Assuming your outf function is within the function or script
var1 = 0;
var2 = 1;
outfAnon = @(x) outf(x, optimValues, state, var1, var1);
opts = optimset('PlotFcns',outfAnon, ...)
For more information on this method or to see other methods including the use of nested functions and global vars (avoid), see this : https://www.mathworks.com/help/optim/ug/passing-extra-parameters.html
[EDIT] Removed a mistake where I included ' @' symbol when entering outfAnon in the opts line.