Matlab 设置用户输入的时间限制

Matlab 设置用户输入的时间限制,matlab,Matlab,我正在做一个项目。它的一部分要求用户对图形做出反应。目标:用户必须在有限的时间内(例如1秒)按键,否则图形将关闭。以下是我到目前为止的情况: test = figure; tic; pause; input = get(gcf, 'CurrentCharacter'); reaction_time = toc; close; 我一直在互联网上寻找增加时限的解决方案。我尝试了而循环和定时器,但我就是想不出正确的方法。我会非常感激的。我认为,经过一些调整,这正是您想要的。代码内部的解释: % Le

我正在做一个项目。它的一部分要求用户对图形做出反应。目标:用户必须在有限的时间内(例如1秒)按键,否则图形将关闭。以下是我到目前为止的情况:

test = figure;
tic;
pause;
input = get(gcf, 'CurrentCharacter');
reaction_time = toc;
close;

我一直在互联网上寻找增加时限的解决方案。我尝试了
循环和
定时器
,但我就是想不出正确的方法。我会非常感激的。

我认为,经过一些调整,这正是您想要的。代码内部的解释:

% Let's define a control struct called S: 
global S; % We need to be able to actually change S in a function, but Matlab passes variables by value.

% Add to S all information you need: e.g. a figure handle 
S.f = figure;  % Add in the figure handle
S.h=plot(rand(10,1));  % Plot something on it  

% Define a boolean flag to capture the click: 
S.user_has_clicked = false; 

% Add a button to the figure - or anywhere else: 
S.pb = uicontrol('style','push','units','pix','position',[10 10 180 40],...
                 'fontsize',14,'string','Change line',...
                 'callback',@pb_callback);

% Define a timer object with a timeout of 3 seconds: 
timer_o = timer('StartDelay', 3, 'TimerFcn', @timer_callback); 

% Start the timer, and continue computing
start(timer_o)

% Some compute code, or simply pause(3); 
while(1)
    pause(1); 
    disp('Computing for another second'); 
end

% The push button callback: 
function pb_callback(varargin) 
global S 
S.user_has_clicked = true; 
disp('Captured a click'); 
end

% The timer callback: 
function timer_callback(timer_o,~) % 
    global S 
    if ~S.user_has_clicked
        disp('Timeout reached with no button click - Closing figure'); 
        close(S.f); 
    else
        disp('Detected user click in timeout callback');
    end
end

您可以使用
while
循环,因为
get(gcf,'CurrentCharacter')
是非阻塞的:

close all

timeout_duration = 5; % Set timeout to 5 seconds.
input = []; % Initialize to empty
duration = 0; % Initialize to 0

test = figure;

tic; % Start measure

%Loop until key pressed or timeout.
while isempty(input) && (duration < timeout_duration)
    duration = toc; % Place the toc here to for excluding the last 1msec
    input = get(gcf, 'CurrentCharacter'); % Return [] if no key pressed
    pause(0.001); %Pause 1msec
end

if isempty(input)
    disp('Timeout!'); % If input = [], it's a timeout.
else
    reaction_time = duration;
    display(reaction_time);
end

close(test)
全部关闭
超时\u持续时间=5;%将超时设置为5秒。
输入=[];%初始化为空
持续时间=0;%初始化为0
测试=数字;
tic;%开始测量
%循环直到按键或超时。
当isempty(输入)和(持续时间<超时\u持续时间)
持续时间=总有机碳;%将toc置于此处,以排除最后1毫秒
输入=获取(gcf,'CurrentCharacter');%如果未按任何键,则返回[]
暂停(0.001);%暂停1秒
结束
如果为空(输入)
disp('超时!');%如果输入=[],则为超时。
其他的
反应时间=持续时间;
显示(反应时间);
结束
关闭(测试)

如果用户成功,将会发生什么?非常感谢!
while
循环工作得很好。