MATLAB: Do I receive an error “Variable output array “varargout” must be a cell array” in a GUI compiled with MATLAB Compiler

gui_mainfcnMATLAB Compiler

I have compiled a GUI created with GUIDE. When executing my GUI in MATLAB I receive no errors. However, after compiling it I receive the following error at runtime:
Error in ==> gui_mainfcn at 197
Error in ==> mygui at 26
Warning: Objects of uitools.uimodemanager class exist - not clearing this class
or any of its super-classes
??? Error using ==> mygui_OutputFcn
Variable output array "varargout" must be a cell array.
Another manisfestation of this error is:
??? Error using ==> mygui>mygui_OutputFcn
Too many output arguments.
Error in ==> gui_mainfcn at 248
Error in ==> mygui at 40

Best Answer

This error is caused by the mygui_OutputFcn not having the proper output variable format.
When a GUI named mygui is created with GUIDE, mygui_OutputFcn is automatically created. This function has a variable number of outputs as specified by the varargout return value. A cell array must be assigned to this variable.
For more information on varargout, please visit the following webpage:
GUIDE creates all the necessary code to assign a cell array to varargout, however if you have modified some of this code, you may get runtime errors.
The reason why this error only occurs in compiled mode is that in compiled mode a return argument is requested. On the other hand, when running the GUI from within MATLAB, generally no return argument is specified. Therefore, the contents of varargout are never checked by the MATLAB interpreter. If you were to execute the GUI as follows from within MATLAB, the same error message would be generated.
ret = mygui
The contents of mygui_OutputFcn should contain the following code.
% --- Outputs from this function are returned to the command line.
function varargout = mygui_OutputFcn(hObject, eventdata, handles)
% Get default command line output from handles structure
varargout{1} = handles.output;
Be sure not to add any code after the assignment to varargout which clears this variable. Also, note that the following code should be present in mygui_OpeningFcn.
% --- Executes just before mygui is made visible.
function mygui_OpeningFcn(hObject, eventdata, handles, varargin)
% Choose default command line output for mygui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);