Clear Filters
Clear Filters

lsqnonlin with multiple start vectors: continue with next start vector if the function computing the objective function sets a "flag"

2 views (last 30 days)
I want to execute lsqnonlin with multiple start vectors by iterating over a for-loop. If the function called by lsqnonlin (here, fun(x)) sets a variable to a specific value, I would like to continue with the next vector. A return statement in fun(x) will return the control to lsqnonlin, but not to the loop from which I called lsqnonlin.
That said, my goal is to forward some information from fun(x) to the place where lsqnonlin is called.
How can I achieve the desired result in my case?
%execute optimization 5 times with different start vectors
for i=1:5
x0=...; %x0 associated with index i
sol = lsqnonlin(@fun(x), x0, lb, ub);
end
function f = fun(x)
%compute objective function f by calling external program
f=...;
%set staus=-1 if something goes wrong when calling the external program
status=-1;
if(status == -1)
%MOVE ON TO i+1 IN THE LOOP ABOVE
end
end
...

Accepted Answer

Walter Roberson
Walter Roberson on 1 Apr 2023
Use error() to cause lsqnonlin to abort. You might need try/catch to contain the error.

More Answers (1)

Piyush Patil
Piyush Patil on 1 Apr 2023
Hello,
Based on what I understood from your question, you want to iterate through the loop only when the "status" is -1.
So, to do that use "while" loop instead of "for" loop and increment the counter of "while" loop only when "status" is -1.
% initilize i to 1
i = 1;
while i<=5
x0=...; %x0 associated with index i
[sol,resnorm,residual,exitflag,output]
= lsqnonlin(@fun(x), x0, lb, ub);
if(exitflag == -1)
i = i+1
end
end

Community Treasure Hunt

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

Start Hunting!