我希望能够分配一个按键,按下该按键将停止我的脚本。我尝试使用getkey,但无法解决问题
答案 0 :(得分:0)
使用鼠标位置作为控制运行时的方式更加方便。
例如,当您将鼠标移到屏幕左边缘时,这将暂停脚本。
mymouse=get(0,'PointerLocation');
if mymouse(1)<4, keyboard;end
您可以将多个边缘位置用于不同的动作。
答案 1 :(得分:0)
一个好的解决方案是创建一个图形,然后为该图形创建一个回调函数,当您按下一个键时,该函数会停止脚本。
例如:
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