MATLAB Answers

How do I exit a loop with a key hit?

407 views (last 30 days)
Harry
Harry on 1 Jul 2013
Commented: Sanders A. on 5 Feb 2020
So I have a loop in my code but I want to exit the loop and move onto the next set of calculations after I hit some key. I know that I could ask for input in the loop, which could confirm whether I could move on or not but that would require me to confirm at each loop which I don't want to be doing.

Answers (4)

Lukas
Lukas on 22 Jan 2020
In a similar way I use wait bat cancel button:
hWaitbar = waitbar(0, 'Iteration 1', 'Name', 'Solving problem','CreateCancelBtn','delete(gcbf)');
for i=1:5
% Some long taking computation
pause(5);
% Check
drawnow;
if ~ishandle(hWaitbar)
% Stop the if cancel button was pressed
disp('Stopped by user');
break;
else
% Update the wait bar
waitbar(i/5,hWaitbar, ['Iteration ' num2str(i)]);
end
end
  1 Comment
Sanders A.
Sanders A. on 5 Feb 2020
I prefer this answer because it doesn't latch on to an existing figure and upon hitting the cancel/'stop now' button delete the figure. This si nice for being able to leave my figures in specific places on my screen and run&stop my animations as I please.
Thank you!!

Sign in to comment.


Vugar
Vugar on 30 Sep 2018

The answer of Jan is almost correct - only one code line is missing:

ButtonHandle = uicontrol('Style', 'PushButton', ...
                         'String', 'Stop loop', ...
                         'Callback', 'delete(gcbf)');
for k = 1:1e6
  disp(k)
  if ~ishandle(ButtonHandle)
    disp('Loop stopped by user');
    break;
  end
pause(0.01); % A NEW LINE
end

Jan
Jan on 1 Jul 2013
Edited: Jan on 1 Jul 2013
You can create a waitbar or any other GUI which contains a button for breaking the loop. Then check a property inside the loop and break is the value chnages. This property could be the existence of the figure or the button as well as the UserData of the button or figure.
ButtonHandle = uicontrol('Style', 'PushButton', ...
'String', 'Stop loop', ...
'Callback', 'delete(gcbf)');
for k = 1:1e6
disp(k)
if ~ishandle(ButtonHandle)
disp('Loop stopped by user');
break;
end
end
  7 Comments
Rik
Rik on 5 Aug 2019
S. Gokhun Tanyer, what is the exact code you tried?

Sign in to comment.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!