MATLAB: How to break out of an infinite loop without terminating the subsequent routine


I would like to interrupt an infinite loop, for example by hitting a key on keyboard, in such a way that the program breaks out of the loop and continues with the rest of the routine.

Best Answer

There is no direct way of breaking an infinite loop in MATLAB, while continuing execution of subsequent commands.
However, the 'currentcharacter' property of a figure can be exploited as a workaround for this problem, as illustrated by the example code below. Character 'q' is used to quit the loop in the following example.
function example
% create a figure that is minimized using position and menubar option
% figure appears as a minimized
% hf is handle to the figure
hf=figure('position',[0 0 eps eps],'menubar','none');
% begin infinite loop
while 1
% compares the current character to q
if strcmp(get(hf,'currentcharacter'),'q')
% force the event queue to flush
If you are already using a graphical user interface (GUI) or figure window in your application, then you may want to consider implementing a "stop" button according to the Related Solution, listed below.