Ending a function after a time duration

6 ビュー (過去 30 日間)
Nathanael  Kazmierczak
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by