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 Center および File ExchangeSolver Outputs and Iterative Display についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by