2015-12-03 80 views
2

我正在嘗試編寫一個腳本,它獲取用戶輸入的指定時間間隔。我下面寫了一個簡單的腳本:在matlab中獲取用戶輸入的時間間隔

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秒的時間。但是如果用戶沒有按照預期輸入任何輸入,這個腳本將無限期地等待。有沒有什麼方法可以在給定的時間間隔內獲得用戶輸入? 在此先感謝!

+0

採取在MATLAB看看'timer':http://www.mathworks.com/help/matlab/ref/timer-class.html – NKN

+0

這是否需要被在命令窗口中還是可以使用簡單的GUI? – excaza

+0

其實我會用Psychtoolbox創建一個實驗,我需要這個用於我的實驗。 – Berkehan

回答

1

來源:http://www.mathworks.com/matlabcentral/answers/96229-how-can-i-have-a-dialog-box-or-user-prompt-with-a-time-out-period

function varargout = timeoutDlg(dlg, delay, varargin) 
% Dialog function with timeout property 
% dlg is a handle to the dialog function to be called 
% delay is the length of the delay in seconds 
% other input arguments as required by the dialog 
% EXAMPLE FUNCTION-CALL 
% To display an input dialog box (REFER MATLAB HELP DOC) with a 
% timeout = 6 second say, the function call would be: 
% 
% [matrix_size_value, colormap_string] = timeoutdlg(@inputdlg, 6, ... 
%        {'Enter matrix size:','Enter colormap name:'}, ... 
%        'Input for peaks function', 1, {'20','hsv'}) 
% Setup a timer to close the dialog in a moment 
f1 = findall(0, 'Type', 'figures'); 
t = timer('TimerFcn', {@closeit f1}, 'StartDelay', delay); 
start(t); 
% Call the dialog 
retvals = dlg(varargin{:}); 
if numel(retvals) == nargout 
     varargout = retvals(:); 
else 
     varargout = cell(1, nargout); 
end 
% Delete the timer 
if strcmp(t.Running, 'on') 
     stop(t); 
end 
delete(t); 
function closeit(src, event, f1) 
disp('Time out!'); 
f2 = findall(0, 'Type', 'figure'); 
fnew = setdiff(f2, f1); 
if ishandle(fnew); 
     close(fnew); 
end 
+0

看來這可能會奏效,謝謝。 – Berkehan