MATLAB: Limit time with tic toc

The program will has 5 different levels of difficulties which correspond to a number of seconds the use has to enter an answer. how i do that with tic toc function?
X=floor(10*rand(1));
Y=floor(10*rand(1));
format short
formatSpec='Vad blir: %2f x %4f \n' ;
tic
fprintf(formatSpec,X,Y)
riktigt_svar=X*Y;
Ditt_Svar=input('Svar:');
t=toc
pause(0.5);
if Ditt_Svar == riktigt_svar
msgbox('Right answer')
else
if Ditt_Svar ~= riktigt_svar
errordlg(['Right answer is',num2str(riktigt_svar)],'Error')
end
end

Best Answer

input() is a blocking function, and there is no good way to timeout on it in MATLAB. The only alternative is to use inputdlg() and use a timer to close it after a specific number of seconds. See the answer to this question: https://www.mathworks.com/matlabcentral/answers/96229-how-can-i-have-a-dialog-box-or-user-prompt-with-a-time-out-period
Here is a short version of the code on that question
f1 = findall(groot, 'type', 'figure');
t = timer('TimerFcn', {@closeit f1}, 'StartDelay', 3);
start(t);
value = inputdlg('myPrompt', 'myTitle');
value = str2double(value{1});
function closeit(obj, ~, f1)
f2 = findall(0, 'Type', 'figure');
fnew = setdiff(f2, f1);
if ishandle(fnew)
close(fnew);
end
stop(obj)
delete(obj);
end