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

4 次查看(过去 30 天)
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
...

采纳的回答

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

更多回答(1 个)

Piyush Patil
Piyush Patil 2023-4-1
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

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by