如何在 Matlab 中稳定等待 Enter/Spacebar/...?

How to have stable wait for Enter/Spacebar/... in Matlab?

我想找到一些稳定的方法来询问在循环结束时按 Enter/Spacebar/... . 我无法使选项 (1-2) 稳定工作。 我不需要任何 GUI 来完成这项任务。 当您可以按下该键时,Matlab 提示中的文本输出。 我尝试了这些选项但没有成功,但它们导致我的代码停滞不前,以至于没有密钥不起作用

while 1 % just indicating here a loop, not in actual code 

% Plotting here 6 Figures, and iterating/updating them in the loop 

% Option 1
% apparent docs: https://se.mathworks.com/matlabcentral/fileexchange/7465-getkey
while getkey ~= 13,
    disp('Enter was not pressed. Try again.'); 
end
disp('Enter was pressed.'); 

% Option 2
% Docs: https://se.mathworks.com/help/matlab/ref/waitforbuttonpress.html
w = waitforbuttonpress;
if w == 0
    disp('Button click')
else
    disp('Key press')
end

end

Matlab: 2016a
OS: Debian 8.5 64 位
硬件:华硕 Zenbook UX303UA

在循环末尾添加pause

以下代码将等到按下 空格键

f = figure;
% The next line is just to hide the fig window away from the screen (not really necessary)
set(f, 'Position', [1e-12 1e-12 1e-12 1e-12]) 

k=0;
while ~k
    k=waitforbuttonpress;
    if ~strcmp(get(gcf,'currentcharacter'),' ');
        k=0;
    end
end
close(f)   %Closing the figure

我对 Sardar_Usama 的 的修改。 根据已接受的答案进行编辑:window 的最小布局、中心位置、最小 window 大小,并且不会因为在等待执行时需要做其他事情而隐藏。 waitforbuttonpress 的停顿在我的动态环境中也不够; pause 有效但不明白为什么

pause(1); % not sure; but this helps in many dynamic cases
% waitforbuttonpress pause is not sufficient

% 
f = figure('Name', 'Press SPACEBAR to continue', 'NumberTitle', 'off', ...
    'ToolBar', 'none', 'MenuBar', 'none', 'Units','centimeters', 'Position',[0 0 10 1]); 
movegui(f,'center');
k=0;
while ~k
    k=waitforbuttonpress; % includes pause in itself so no pause() need
    if ~strcmp(get(gcf,'currentcharacter'),' ');
        k=0;
    end
end
close(f)