Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a timer for input() function in MATLAB?

Tags:

timer

matlab

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

like image 538
alpha Avatar asked Oct 16 '25 19:10

alpha


1 Answers

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
like image 80
Byte Ninja Avatar answered Oct 18 '25 08:10

Byte Ninja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!