编写一个在按下返回时将突破for循环的函数。 [重复]

问题描述 投票:1回答:1

我正在编写一个matlab脚本,它将在for循环中执行计算,但是当输入'return'时,它希望它跳出for循环。我发现了一个能够监听击键并修改它的函数,以便知道何时按下'return',但我无法弄清楚如何让它控制主脚本中发生的事情。

伪代码:

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
matlab loops keyboard-events
1个回答
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。

© www.soinside.com 2019 - 2024. All rights reserved.