Хорошим решением является создание фигуры, а затем создание функции обратного вызова для этой фигуры, которая останавливает ваш скрипт при нажатии клавиши.
Например:
function stoptest
%% Setup program
% create a figure for the application
myfig=figure;
% specify a callback function for the figure which will
% listen for key presses
set(myfig,'KeyPressFcn', @stopkey);
data = []; k = 0;
%% Main Program Loop
% Use a global variable to control the loop
global RUNTEST;
RUNTEST=1;
fprintf(1,'Start MyFunction. Press alt-s to stop.\n');
while RUNTEST == 1
% do whatever the loop does
% maybe plot some data in the window
% if the operator presses a key, it calls the figure callback function
data = [data; k rand(1)];
plot(data)
drawnow;
end
function [] = stopkey(src,evnt)
% STOPKEY is a callback function that acts as the stop condition to cleanly
% exit the test. It sets the value of RUNTEST to 0 when the user presses
% <alt-s> in the progress figure (or <option-s> on a Mac).
global RUNTEST;
if length(evnt.Modifier) == 1 && strcmp(evnt.Modifier{:}, 'alt') && strcmp(evnt.Key,'s')
RUNTEST = 0;
fprintf('\nMyFunction: Operator quit by pressing (alt-s)\n');
end
return