If you're using tic, toc, and var=input('prompt'), is there a way for toc to interrupt the user input if they take too long to answer?
4 views (last 30 days)
Christina Diersing on 28 Jul 2021
Hi, I'm working on a project where I have to time people's answers for math problems. Currently, I'm working on 1 problem where they have up to 20 seconds to answer. Is there a way to have Matlab interrupt and tell the user they took too long to answer? So, if they don't answer in 20 seconds, a line will pop up telling them they took too long?
This is the code I have so far for it, but it won't tell the user they took too long until after they input an answer.
close all; clear all; clc;
fprintf('Directions: Complete the following Math problems in your head, then type the answer on the number pad. You will have up to 1 minute to answer each question. Please press any button to continue.\n\n')
ECorAns=76*10; %correct answer
easAns=input(' 76 \n x10 \n ')
if toc(teass) >= 20
fprintf('Out of time');
fprintf(' \n Correct! Good Job! \n');
fprintf('\n End \n')
I think I have it set so the code will remember teass once the code has completely run, so I can record the data.
Cam Salzberger on 28 Jul 2021
You could try using an inputdlg to ask the question, instead of keeping it in the command window. You could get the handle to the dialog box and close it if they take too long.
For a little more customization, you could create your own figure or uifigure pop-up to ask the question.
More Answers (2)
TADA on 28 Jul 2021
Edited: TADA on 28 Jul 2021
Its possible, not using toc though.
The problem is this, once your code reaches the input function it freezes in that line and waits for keyboard interaction.
the next line of code is only run after input is returned so toc is not reached at all.
you can use a timer and then proggramatically type the enter key on the "keyboard" using JAVA
timeout = timer();
timeout.ExecutionMode = 'singleShot';
timeout.TimerFcn = @doTimeout;
timeout.StartDelay = 10;
s = input('type something:', 's');
function doTimeout(tmr, ea)
This small example shows how to stop the input function forcefully after 10 seconds using the trick I mentioned.
This could backfire though if the user starts typing then the timer fires and stops the user in the middle.
Walter Roberson on 28 Jul 2021
Two timer based solutions are shown in https://www.mathworks.com/matlabcentral/answers/119067-how-can-i-set-a-time-for-input-waiting#answer_318457 and https://www.mathworks.com/matlabcentral/answers/95301-how-can-i-implement-a-timer-dependent-input-request-in-matlab
I discuss a list of other possibilities provided by the third party Psychtoolbox