s:
Here is a trick that should work: Somewhere in the GUI, like in its OpeningFcn
for instance, initialize a flag named for example StopNow
to false
and store it in the handles structure of the GUI. Then in the loop that takes long to execute, put an if
statement with a call to return
whenever the flag is set to true
. That will stop the execution of the loop and you will have access to your data. You can make a pushbutton to change the flag value.
Sample code: I made a simple GUI that starts enumerating digits in a for loop and printing them in a text box. When you press the STOP button, the flag is set to true and the loop stops. If something is unclear please tell me.
function StopGUI clear clc close all %// Create figure and uielements handles.fig = figure('Position',[440 500 400 150]); handles.CalcButton = uicontrol('Style','Pushbutton','Position',[60 70 80 40],'String','Calculate','Callback',@CalculateCallback); handles.StopButton = uicontrol('Style','Pushbutton','Position',[250 70 80 40],'String','STOP','Callback',@StopCallback); %// Initialize flag handles.StopNow = false; handles.Val1Text = uicontrol('Style','Text','Position',[150 100 60 20],'String','Value 1'); handles.Val1Edit = uicontrol('Style','Edit','Position',[150 70 60 20],'String',''); guidata(handles.fig,handles); %// Save handles structure of GUI. IMPORTANT function CalculateCallback(~,~) %// Retrieve elements from handles structure. handles = guidata(handles.fig); for k = 1:1000 if handles.StopNow == false set(handles.Val1Edit,'String',num2str(k)); pause(.5) %// The pause is just so we see the numbers changing in the text box. else msgbox('Process stopped'); return end end guidata(handles.fig,handles); %// Save handles structure of GUI. end function StopCallback(~,~) %// Retrieve elements from handles structure. handles = guidata(handles.fig); handles.StopNow = true; guidata(handles.fig,handles); %// Save handles structure of GUI. end end
Screenshot after pressing the STOP button:
Hope that helps!