Matlab GUI Tutorial - How to Stop a Long Running Function without using “control + c”
07 Dec 2007 Quan Quach 21 comments 14,389 views
Introduction
This tutorial will show you how to stop a function that is running from within a GUI. Most of the time, when we want to stop a function from running, we simple use the almighty "control + c" combination. But all this really does is kill the entire process thread, which may sometimes be undesirable. This tutorial will show you how to stop a function with the press of a button without killing the GUI. This feature is most helpful when you have long running “for” or “while” loops.
This tutorial is written for those with some experience creating a Matlab GUI. If you’re new to creating GUIs in Matlab, you should visit this tutorial first. Basic knowledge of Matlab and an understanding on how data is shared among callbacks is highly recommended. Matlab version 2007a is used in writing this tutorial. Both earlier versions and new versions should be compatible as well (as long as it isan’t too outdated). Let’s get started!
The Example Files and Code
-
First, download the sample GUI here. Unzip the files and place them wherever you please.
-
Now, type
guideat the command prompt.
-
Choose to open the sample GUI by clicking on “Open Existing GUI”. Click on “Browse” to locate where you saved the GUI files.

-
Here is what the GUI should look like when you open it:

-
Click on the
icon on the GUI figure to bring up the accompanying .m file. -
Now, add the following code to start_pushbutton_Callback. In order for this interrupt function to work properly, we must use the UserData property. All GUI components, including menus, and the figure have a UserData property. You can assign any valid MATLAB value to the UserData property. Thus, in this case, we are using the UserData property to store the flag variable value.
%initialize the flag variable set(handles.start_pushbutton,'UserData',1); %while the flag variable is one, the loop continues while (get(handles.start_pushbutton,'UserData') ==1) %increments the counter temp = str2num(get(handles.counter_text,'String')); temp = temp + 1; set(handles.counter_text,'String',num2str(temp)); %"flushes the event queue" and updates the figure window %since Matlab is a single thread process, this command is requierd drawnow end guidata(hObject, handles);
-
Now, add the following code to stop_button_Callback.
%toggle the flag variable so that the other process will stop set(handles.start_pushbutton,'UserData',0); guidata(hObject, handles);
-
Now, save your .m file and run the GUI. You should see the following GUI appear

-
Press the start button to activate the GUI. You should see the text box displaying a number that is rapidly increasing. Whenever you want the process to stop, simply press the stop button.

-
You can resume the GUI by pressing the start button again.
Download Source Files
Click here to download the source files.
This is the end of the tutorial.
21 Responses to “Matlab GUI Tutorial - How to Stop a Long Running Function without using “control + c””
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


Thanks a lot! It was very helpful.
That can be a very useful technique. Can you give us your opinion on what would be a good way to make a generic pause/play gui that works with an external calculation?
Thanks,
-naor
I have a audio signal which sometimes taking too long to load, so i need to set a stop button just in case the user wants to stop running the program. However, if i use the method as shown above, the sound will nonstop looping in the while loop n having multiple repeat sound until i click the button. is there any way that the sound will oni produce once and also to have a stop button to stop the long prog to run (like how ctrl c function )??
hehe this is a clever little trick. thanks, this is going to be very helpfull as I will put it to use immediately.
Thank you extra very much! I was simply searching for something like ‘drawnow’.
First I’d like to say thanks, this is very useful, as is your entire site. Keep up the good work!
I have used your above approach to put “play”/”pause”/”reset” buttons on a GUI that continually updates graphical plots as data changes over time.
However, I find that unless I put a fairly large pause (pause(0.2), say) statement in the loop, the GUI does not respond to button presses - and even with the pause its necessary to repeatedly press.
I am new to Matlab. In Java I would have the button press wait on the event queue, but Matlab is single-threaded, right? So, is there a more elegant way, or am I stuck with pause?
Thanks a lot!!!
This was actually helpful not as a start/stop (I use uiwait & uiresume for that), but more so to dynamically update a ‘time’ counter as the loop moves and make it visible to the user. Thanks!
Glad it was helpful!
Thank’s a lot, this seems a simply example but this gonna rise the development of the newer user of guide & gui. This gonna help me with a PaP motor.
[...] Read input without wait from the keyboard in Matlabs main thread, here and see the related tutorial. [...]
Hi!
It’s very helpful and easy solution!
Thanks
Thanks a lot for this site
A saver website :D, easy to follow and results right away … Thanks and keep it up
all your tutorials have been so helpful.
easy to understand and very informative.
good luck in all your endeavors.
thank you very much!
thanks. it’s really helpful.
I’m using it in a similar application where I need to stop a video from continuous playing.
Thank you very much!
This trick helped me a lot!
thanks alot for this website,t’s very helpful
Hi sir. i have a problem with my stop button in my GUI program. the program codes are listed down below.When pushbutton1 is pressed, it runs the device and plots the waveform. But where do i place the codes for the stop button and how? I have tried putting while and if, setting the user data to 1, but it failed.
% — Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.pushbutton1,’UserData’,1);
switch get(handles.popupmenu1,’Value’)
case 1
serobj = serial(’COM12′) ;
;
serobj.Baudrate = 19200;
set(serobj, ‘Parity’, ‘none’) ;
set(serobj, ‘Databits’,
set(serobj, ‘StopBits’, 1) ;
set(serobj, ‘Terminator’,'CR’);
set(serobj,’Readasyncmode’,'continuous’);
set(serobj,’InputBufferSize’, 480012)
set(serobj, ‘OutputBufferSize’,480012) ;
set(serobj, ‘Timeout’,1 ) ;
disp(’Connection to Syringe Pump through RS232 interface established’);
get(serobj) ;
fopen(serobj) ;
fprintf(serobj,’rat MH’);%set the infusion rate unit
fprintf(serobj,’VOL ML’);%set the volume unit
fprintf(serobj,’DIA 10.25′); %settings of the pump
%fprintf(serobj,’rat 1′);%default infusion rate of the pump to 1ML/H for machine calibration
%fprintf(serobj,’run’);%run the syringe pump
PI1;% the first PI controller is set to be the default controller
m=0;
%Loop for the controller selection, determine the Ki and Kp
for m=1:3
Condition;
Infusion_input;%calculate out the infusion rate.
fprintf(serobj,’rat %s\r’, num2str(u1,’%.2f’));%convert the infusion rate u1 to string, the /r is for the setting CR (Carriage Return)
%fprintf(serobj,’rat’); %send the specific parameter you want to get from the machine.
%out=fscanf(serobj)%Scan the machine port and get the value of the specific parameter.
for j=1:n2
Differential;
pause(1); % the pause time inbetween each calculation.
if ((t1>=90)&&(t1<=180)) %take samples of the MAP trajectory during 90s to 180s.
N=average_slop(t3,y);% calculate the average slop of the samples to compare with a predefined range to detemine which controller should be selected.
if(Ki==-0.0005)&&(Kp==-0.026)
compare;
break;
elseif(Ki==-0.0018)&&(Kp==-0.0500)
compare2;
break;
else
compare3;
break;
end
end
end
break;
end
%use the selected controller Ki,Kp values to recalculate the infusion rate.
fprintf(serobj,’run’);
Condition;
for j=1:n2
Infusion_input;%take the calculated infusion rate u1 value.
axes(handles.axes1)
axis([0 100 90 180]);
xlabel(’time(min)’);
ylabel(’MAP(mmHg)’);
y=y0+y(1);
plot(j,y,’-.r’);
hold on;%hold the point.
axes(handles.axes2)%plot the Infusion rate vs Time
axis([0 100 0 10]);
xlabel(’time(min)’);
ylabel(’SNP Infusion Rate(mmHg/hr)’);
plot(j,u1,’-');
hold on;%hold the point.
Differential;
fprintf(serobj,’rat %s\r’, num2str(u1,’%.2f’)); %send the infusion rate to the pump if the last controller is chosen.
fprintf(serobj,’rat’);
out=fscanf(serobj)
pause(1);
end
fprintf(serobj,’stp’)
delete(serobj);
Hi sir. i have a problem with my stop button in my GUI program. the program codes are listed down below.When pushbutton1 is pressed, it runs the device and plots the waveform. But where do i place the codes for the stop button and how? I have tried putting while and if, setting the user data to 1, but it failed.