MATLAB: Return data from GUIDE on figure close

delayguiguideMATLABoutputoutputfcnuiwait

I have a GUIDE generated UI in which I have wired up one of computed values, to handles and return it through automatically generated callback OutputFcn. When I run my UI, it computes the value and returns it to the command window immediately. The UI has interactive controls which will modify the output value, but it is not returned after the interactive controls are manipulated.
When I add uiwait(handles.figure1), then OutputFcn is not called until close, which is the desired behavior. Unfortunately when I do this the handles passed into OutputFcn is empty. When I omit the uiwait command from OpeningFcn, then the handles object passed to OutputFcn is populated as expected.
It seems that if OutputFcn is called while the figure is still open, then the handles object exists and can be referenced, however, if OutputFcn is not called until I close the figure, then the handles object points to a closed figure and I can no longer reference it.
Any advice to resolve this? Thanks!

Best Answer

To delay a GUIDE-GUI output until the GUI is closed, follow these steps. A functional demo is attached that produces an empty GUI and returns a hard-coded output when the GUI is closed. See comments in the m-file for help.
1) If your GUI does not already have a close request function, add one from within GUIDE by opening your GUI in GUIDE, right click the figure background, select View Callbacks, and the select CloseRequestFcn.
2) In the ..._OpeningFcn
function demoGui_OpeningFcn(hObject, eventdata, handles, varargin)
. . .
uiwait(); % add this to the end
3) In the ..._outputFcn
function varargout = demoGui_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
delete(hObject); % add this
4) In the ..._CloseRequestFcn you created from GUIDE,
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% delete(hObject); % Remove this
handles.output = 3.1415926; % Produce or grab your outputs
guidata(hObject, handles); % Store the outputs in the GUI
uiresume() % resume UI which will trigger the OutputFcn
[Original answer has been edited]