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

回答(2 个)

Walter Roberson
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
daniele frollani 2012-10-17
Hello Walter, first of all thanks for your answer, I really appreciated that. I solved my problem in this way:
a=1;
for i=1:5
.....
[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
end
I looked for the try/catch construction but I didn't understand how to apply it to the problem. Even though my problem has been solved (and thanks again) it would be helpful if you can give me a short example of the try/catch condtruction.
  1 个评论
Walter Roberson
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by