在Matlab中按时间间隔获取用户输入
问题描述:
我正在尝试编写一个脚本,以在指定的时间间隔内获取用户输入.我写了一个简单的脚本,如下所示:
I'm trying to write a script which gets user input for a specified time interval. I wrote a simple script as below:
timeEllapsed=0;
Count=0;
while 1
tic
input('press enter');
timeEllapsed=timeEllapsed+toc;
Count=Count+1;
if(timeEllapsed>5)
break;
end
end
disp ('result is:')
disp(Count)
第一次输入和最后一次输入之间的时间少于5秒时,此脚本将获得用户输入.但是,如果用户未按预期输入任何输入,则此脚本将无限期等待.有什么办法可以在给定的时间间隔内获得用户输入吗? 预先感谢!
This script gets user input, when the time between first and last input less than 5 seconds. But this script waits indefinitely if user doesn't enter any input as expected. Is there any way to get user input for exactly given time interval? Thanks in advance!
答
这是一个自包含的解决方案...
This is a self contained solution...
function output = timeinput(t,default_string)
% TIMEINPUT
% Input arguments:
% t - time delay
% default_string - string which is returned if nothing is entered
%
% Examples:
% If a string is expected
% x = timeinput(20,'no input')
% If a number is expected
% x = str2num(timeinput(20,'1'))
%
if nargin == 1
default_string = '';
end
% Creating a figure
h = figure('CloseRequestFcn','','Position',[500 500 200 50],'MenuBar','none',...
'NumberTitle','off','Name','Please insert...');
% Creating an Edit field
hedit = uicontrol('style','edit','Units','pixels','Position',[10 15 180 20],'callback','uiresume','string',default_string);
% Defining a Timer object
T = timer('Name','mm', ...
'TimerFcn','uiresume', ...
'StartDelay',t, ...
'ExecutionMode','singleShot');
% Starting the timer
start(T)
uiwait(h)
% Defining the return value
output = get(hedit,'String');
% Deleting the figure
delete(h)
% Stopping and Deleting the timer
stop(T)
delete(T)
要运行5秒钟的超时输入,只需输入:
To run a 5 seconds timeout input, just write:
x = timeinput(5,'no input')