MATLAB: How to Stop Fmincon from GUI

fminconguiguidehobject;Optimization Toolboxstop

How to stop fmincon from a pushbutton in a Matlab Gui?
The explaination posted here at the botton does not work, and can not work, as hObject never is passed into the outputfunction
function stop = outfun(x,optimValues,state)
stop = false;
% Check if user has requested to stop the optimization.
stop = getappdata(hObject,'optimstop');
Is there a way to stop the execution of the fmincon algorithm from a Pushbutton? Thanks a lot. Ravi

Best Answer

Ravi - I suspect that the example is only meant to provide an idea of how to do this given that you could have created your GUI either using GUIDE or using the programmatic approach. If you are using GUIDE, then you can always pass in hObject as an additional input to the outfun. For example, suppose that you have a start push button to start the optimization where you create the options (for fmincon) and start the optimization. For example,
function start_pushbutton(hObject, eventdata, handles)
% do some stuff
% create the options
opts = optimoptions(@fmincon,'OutputFcn','{@outfun,hObject});
% start the optimization
Then, you would change the function signature of your outfun to be
function stop = outfun(x,optimValues,state,hObject)
Here, it is assumed that you have created the outfun in the same m-file as for your GUI. Now rather than using getappdata (which forces you to have called setappdata to update hObject with the state of stop), I would use guidata to get the handles structure as
function stop = outfun(x,optimValues,state,hObject)
stop = false;
handles = guidata(hObject);
if isfield(handles,'optimstop')
stop = handles.optimstop;
end
And so your stop button callback would look something like
function stop_pushbutton(hObject, eventdata, handles)
handles.optimstop = true;
guidata(hObject,handles);
In the above we set the optimstop field and then save that change to the handles structure.
I haven't tried the above (since I don't have the Optimization Toolbox) but I think that it can be made to work for your implementation.