我正在编写一个matlab脚本,它将在for循环中执行计算,但是当它返回'时,它希望它能够脱离for循环。进入。我找到了一个能够听取击键并修改它的功能,以便知道何时返回'按下了,但我无法弄清楚如何让它控制主脚本中发生的事情。
伪代码:
h_fig = figure;
set(h_fig,'KeyPressFcn',@myfun)
for ii = 1:50
break when enter is pressed
end
function y = myfun(src,event)
y = strcmp(event.Key,'return');
%disp(event.Key);
if y == 1
fprintf('Enter key pressed')
return
end
end
答案 0 :(得分:0)
您似乎只是在创建窗口,因此您可以捕获返回键。如果是这种情况,则有一个更好的选择:kbhit
(在Octave中,内置了一个具有相同名称的类似函数)。只需将文件交换提交中的kbhit.m
文件复制到当前文件夹(或可以使用addpath
添加到MATLAB路径的任何目录),然后执行以下操作:
kbhit('init');
for ii = 1:50
if kbhit == 13
break
end
% computations here...
end
如果你想要使用一个窗口,正确的方法是轮询"CurrentCharacter" property of the figure window:
h_fig = figure;
set(h_fig,'CurrentCharacter','') % use this if the figure has been around for longer, to reset the last key pressed
for ii = 1:50
drawnow % sometimes events are not handled unless you add this
if double(get(h_fig,'CurrentCharacter'))==13
break
end
% computations here...
end
我无法让上述代码在Octave中运行,似乎即使使用drawnow
它也不会更新图形属性,但不确定原因。但我相当确定上述内容适用于MATLAB。