The script below waits until a user press a key ('y', 'n', or any other character) and/or the Enter key:
prompt = 'Do you say yes or no? y/n[n]: ';
txt = input(prompt,'s');
However, I like it to automatically select n
after a certain amount of time (e.g. 10 or 20 sec) instead of it waiting indefinitely.
I was looking at this post (Set a time limit for user input) but get(gcf, 'CurrentCharacter');
opens a figure window, which I don't like to have.
Is there a way to set a timer for input()
function or is there another way to get a user input (for example, where I can use a while loop and pause()
)?
I'm using MATLAB R2020a
You can create a timer()
function that executes after a specified duration, and within that function, simulate the keypress event:
duration = 10; % sec
t = timer('StartDelay', duration, 'TimerFcn', @timeFunc);
prompt = 'Do you say yes or no? y/n[n]: ';
start(t);
txt = input(prompt,'s');
stop(t);
delete(t);
if isempty (txt), txt = 'n'; end
% Simulate the Enter keypress
function timeFunc(~, ~)
robot = java.awt.Robot;
robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);
end