why is the variable order in a user defined function important in lsqnonlin optimisation?
Show older comments
I have a script which purpose is to optimise a fit of a function (func), in the function, beta0 is the input initial value for two coefficients. And y1, y2, y3 are data in column format (604X1). My codes for lsqnonlin optimisation and my function (func) looks like this:
[beta,resnorm,residual,exitflag,output,lambda,jacobian] = lsqnonlin(@Func,beta0,lb,ub,[],y1,y2,y3);
ci = nlparci(beta,residual,jacobian);
function f1 = Func(beta,y1,y2,y3)
f1 = y2 - beta(1)*y1 - beta(2)*y3 ;
end
when the input for Func writen in this way "Func(beta,y1,y2,y3) ", I optain the correct coefficients.
however if the variable order in the input for Func change to "Func(y1,y2,y3,beta) ", it returns with wrong coefficients.
Why does the order in the self defined function important for lsqnonlin fitting?
And, what is the relationship between the Func variables input order and lsqnonlin variables input order?
Thank you !
Accepted Answer
More Answers (1)
Stephen23
on 5 May 2021
"Why does the order in the self defined function important for lsqnonlin fitting?"
In some languages inputs can be specified by the input name, but MATLAB only has positional input arguments: the input argument names have no real syntactic importance. This means if you change the order then the inputs values are supplied in different positions. This is a very basic MATLAB concept: you will not get very far if you keep moving inputs around.
"what is the relationship between the Func variables input order and lsqnonlin variables input order? "
None, because you are using an obsolete syntax which is discouraged and has not been documented for many years.
The recommended ways to pass extra parameters are explained here:
The most common approach is to use an anonymous function:
y1 = ..;
y2 = ..;
y3 = ..;
fun = @(x)Fun(x,y1,y2,y3);
[..] = lsqnonlin(fun,beta0,lb,ub);
..
function f1 = Func(beta,y1,y2,y3)
f1 = y2 - beta(1)*y1 - beta(2)*y3;
end
3 Comments
Xiu Wen Kang
on 6 May 2021
Stephen23
on 6 May 2021
"Why is that the "function f1 = Func(beta,y1,y2,y3)" becomes obsolete syntax?"
It isn't, there is absolutely no problem with defining a function like that (tip: read the function documentation).
What is obsolete is specifying the objective function parameters as extra inputs to lsqnonlin (or and ODE solver, or similar): that syntax is obsolete, has been removed from the documentation, and should not be used for any new code. The documentation that I linked to shows the recommended approaches for parameterizing objective functions.
Xiu Wen Kang
on 6 May 2021
Categories
Find more on Get Started with Curve Fitting Toolbox 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!