Stopping fmincon based on timer
9 ビュー (過去 30 日間)
古いコメントを表示
Hi, I asked this before and accepted an answer before having some trouble implementing the code, so I think I need to ask again...
I'm trying to terminate fmincon.m after a certain amount of time has elapsed, and the answer was to use an output function which will flag for the iteration to stop based on tic/toc, but I'm having trouble doing this.
My current attempt is:
function stop = outfun()
stop = false;
if toc > 50
stop = true;
end
My error message is confusing since I have no input arguments:
??? Error using ==> outfun
Too many input arguments.
I want the iteration to stop after the timer reaches 50. There is a "tic" just before fmincon is called, and I'm not sure that it's being passed to outfun. I don't know any other way to use tic/toc without requiring an intermediate variable having to be passed to the function. For all my other code I use
t = tic;
while toc(t) < limit
[code]
end
But I can't figure out how to get t into outfun.
Thanks for any help
0 件のコメント
回答 (3 件)
Ryan G
2012 年 11 月 27 日
It looks like you are trying to replicate a timer object which is already available in MATLAB. Perhaps you should try using that instead and you may see better results.
Sean de Wolski
2012 年 11 月 27 日
Hi Michael,
Here is a small example that does this with a timer:
function x = demoFMINCONwithTIMER
options = optimset('Display','iter','Algorithm','Interior-Point'); %for show
setappdata(0,'FMINCONsStopFlag',false); %stopping flag is false
T = timer('startdelay',10,'timerfcn',@(src,evt)setappdata(0,'FMINCONsStopFlag',true)); %after 10 seconds change the flag to true
start(T); %start the timer, T minus 10 seconds!
x = fmincon(@objfun,[500 5000 40],[],[],[],[],[-10000 -10000 -10000],[10000 10000 10000],[],options);
function w = objfun(x)
pause(0.5); %force it to wait
StopFlag = getappdata(0,'FMINCONsStopFlag'); %get stop flag
if StopFlag
error('Time elapsed')
end
w = sum(sin(x)); %simple objective function
end
end
Copy this into an *.m file and run it. And for more information on timers:
doc timer
0 件のコメント
Matt J
2012 年 11 月 27 日
編集済み: Matt J
2012 年 11 月 27 日
My error message is confusing since I have no input arguments:
That's precisely the problem. You're supposed to have input arguments. The documentation on Output Functions will tell you that the output function has to be written with a very specific input syntax, including 3 input arguments. FMINCON is trying to pass these arguments to the output function you supplied and is getting errors when it won't accept them.
But I can't figure out how to get t into outfun.
I'm not sure that calling toc, as you are now doing, will present any problems. However, there are general techniques for passing fixed parameters to functions in MATLAB
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!