How can I go on with my code even if fsolve does not find a solution?
8 次查看(过去 30 天)
显示 更早的评论
Hello everyone, this is something i've been looking for ages and for whihc I still haven't found a solution. The problem is easy to explain: consider I have a code like this:
- a=1;
- for i=1:5
- .....
- sol = fsolve(@myfun,x0,options,....)
- if 'fsolve can't find the solution or there is any error'
- sol(1) = 1;
- sol(2) = 1;
- a = a+sol(1)-sol(2);
- else
- a = a+sol(1)-sol(2);
- end
- end
Let's pretend that if there is not a solution for fsolve this means I somehow know the values. So if fsolve doesn't find a solution or it gives any error (such as Error using trustnleqn (line 28) Objective function is returning undefined values at initial point. FSOLVE cannot continue.Error in fsolve (line 399) [x,FVAL,JACOB,EXITFLAG,OUTPUT,msgData]=...) I just want to go on with the code like nothing has happened. Instead fsolve always kicks me out of the program.
I would be grateful if anyone could help me. Regards, Daniele
0 个评论
回答(2 个)
Walter Roberson
2012-10-16
Use the three output form of fsolve() and look for a negative exitflag.
If fsolve() is generating an error() then use try/catch to contain the error.
daniele frollani
2012-10-17
1 个评论
Walter Roberson
2012-10-17
try
[sol,err,flag] = fsolve(@myfun,x0,options,....)
if flag<0 || flag==0
sol(1) = 1;
sol(2) = 1;
a = a+sol(1)-sol(2);
else
a = a+sol(1)-sol(2);
end
catch ME
sol(1) = 1;
sol(2) = 1;
a = a+sol(1)-sol(2);
end
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!