How can I go on with my code even if fsolve does not find a solution?

3 views (last 30 days)
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

Answers (2)

Walter Roberson
Walter Roberson on 16 Oct 2012
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 on 17 Oct 2012
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 Comment
Walter Roberson
Walter Roberson on 17 Oct 2012
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

Sign in to comment.

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!