Ending a function after a time duration

6 vues (au cours des 30 derniers jours)
Nathanael  Kazmierczak
Nathanael Kazmierczak le 21 Juin 2016
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".

Réponses (2)

Chad Greene
Chad Greene le 21 Juin 2016
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 commentaire
Nathanael  Kazmierczak
Nathanael Kazmierczak le 21 Juin 2016
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.

Connectez-vous pour commenter.


Chad Greene
Chad Greene le 21 Juin 2016
Another option is simply
pause(2)
to wait two seconds.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by