MATLAB Answers

How can i set a time for "input" waiting?

115 views (last 30 days)
Nazariy
Nazariy on 25 Feb 2014
Edited: Anders Olsen on 29 May 2018
I have:
a=input('>>','s')
and MatLab waits for my input information till the infinity, but I need it to wait only first 2 seconds, if no input arguments - ignore "input" comand.
I need you help!

Answers (3)

Iain
Iain on 25 Feb 2014
I'm not sure if there is a direct way.
You can do it in a slightly different way.
tic
disp('Press space to enter what you need to before 5 sec passes')
pause(5)
v = toc;
if v < 5
disp('space got pressed in time.')
a=input('>>','s');
else
disp('space wasn''t pressed')
end
It means that the program doesn't pause for too long, and gives the user as long as they need to enter what they need to.
  3 Comments
Anders Olsen
Anders Olsen on 3 May 2018
I don't see how this would work. As Nazariy points out, specifying a time argument for pause, removes the ability to break the pause with a keypress.

Sign in to comment.


Ameer Hamza
Ameer Hamza on 3 May 2018
Here is a solution based on timer callbacks and simulated keypresses.
  • The following function will simulate an Enter keypress whenever called. Save this function on MATLAB path
function pressEnter(HObj, event)
import java.awt.*;
import java.awt.event.*;
rob = Robot;
rob.keyPress(KeyEvent.VK_ENTER)
rob.keyRelease(KeyEvent.VK_ENTER)
end
  • Then in your code, attach the pressEnter function to the timerFcn of a timer. For example
t = timer('ExecutionMode', 'singleShot', 'StartDelay', 5, 'TimerFcn', @pressEnter);
start(t);
x = input('Enter:', 's');
stop(t);
delete(t);
This code will start a single shot timer and after 5 seconds, it will simulate an Enter keypress and stop the blocking input command. This, however, has a disadvantage that no matter what user types, the Enter key press will be simulated after 5 seconds, therefore user input will be interrupted.
  8 Comments
Anders Olsen
Anders Olsen on 29 May 2018
Alright. I'm using R2016a, so that might be it. But thanks a lot for the suggestion! Maybe I'll get it to work at some point.

Sign in to comment.


Jan
Jan on 28 May 2018
Using the command window and timer is a good idea. But it is much easier, if you do not use the command window, but a GUI with a timer. Then you do not have to emulate a pressed Enter key, but can request the current state of an edit field. Note that the 'String' property is not updated during the editing, but only if Enter was pressed or another GUI element is selected.
Is a GUI a working alternative for you?

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!