Ending a function after a time duration

조회 수: 6 (최근 30일)
Nathanael  Kazmierczak
Nathanael Kazmierczak 2016년 6월 21일
댓글: Nathanael Kazmierczak 2016년 6월 21일
I have a function that, for unknown reasons, is prone to stalling at a certain stage. I would like to force the function to return control to the caller if the function has not finished within, say, one second. I have tried executing variations on the following within the function, but none of them seem to actually return control to the caller. With the code printed below, I obtain the error given below. Any suggestions would be greatly appreciated.
t = timer('TimerFcn',evalin('caller','return'),'StartDelay',1);
start(t)
Error using searchmodels (line 172)
Error: Illegal use of reserved keyword "return".

답변 (2개)

Chad Greene
Chad Greene 2016년 6월 21일
What about this?
waitseconds = 2; % <-Enter number of seconds to wait.
starttime = now;
while now<starttime+waitseconds/86400
disp running
end
disp done
The now function gives the current time in units of days, so dividing by 86400 converts waitseconds to days.
  댓글 수: 1
Nathanael  Kazmierczak
Nathanael Kazmierczak 2016년 6월 21일
Where do you suggest adding the code; within the caller or the function itself? I placed your while loop in the caller and placed the function next to "disp running", and I'm finding that the while loop doesn't seem to terminate the program unless the function completes its operation (otherwise you never get back to the beginning of the while loop to evaluate whether it has taken too long.) When the function bogs down, I have no way of predicting where it will be along any loop, and I can't guarantee that it will calculate any further to reach the end of the loop.

댓글을 달려면 로그인하십시오.


Chad Greene
Chad Greene 2016년 6월 21일
Another option is simply
pause(2)
to wait two seconds.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by