issues solving two interdependent optimization problems with nested functions
7 views (last 30 days)
Show older comments
Hi,
I am trying to write a nested function to do the following:
- Solve a series of equation using fsolve - find values of a dependent variable (vector x) for which a list of equations are all set to 0
- These equations depend on some external parameters, a couple of which I need to solve a minimization problem for.
- In particular, I would like to use lsqnonlin to minimize the distance between some model output (functions of the x vector mentioned above) and some external data targets that I am trying to match. This should provide me with the missing parameters.
As the two problems are interdependent, I thought nested functions would work here but I am struggling, never having used these before. I copy some example code that I tried with only one component for x and 2 parameters.
function [param,xsol] = callfun(x0,par,trgt)
param=lsqnonlin(@(par)nestedf,par,trgt);
xsol = fsolve(@(x)mainf,x0,param);
function F=mainf(x,param)
F=x^2*param(1)+param(2);
@nestedf;
function G=nestedf(param,targets)
calib(1,1)=param(1)*x;
calib(2,1)=param(2);
G=(calib-targets);
end
end
end
Besides various different error messages and moving things around and out of the function itself, I am not convinced this actually does what I have in mind. For sure I am not calling the functions correctly in the outer one. I thought it would have to be something like:
- Starting from a guess of x0, par0 and some targets, call an lsqnonlin solver to find the parameters that minimize the distance from the targets for those guesses
- Call an fsolve to find the x for which function F is 0, given those parameters.
- Repeat these processes until both have converged.
Any help would be greatly appreciated, thanks!
0 Comments
Accepted Answer
Andrew Ouellette
on 11 Nov 2022
Hello,
From your description, it sounds like you would like to solve a contrained optimization problem. This is, you would like to minimize some objective function while keeping some equality constraints true.
You likely will have the most success with using the "fmincon" function:
The "fun" input to "fmincon" will be the distance you were previously trying to minimize with "lsqnonlin" (or rather, the sum of the residuals squared), and the contraints you were previously trying to solve for using "fsolve" can be placed in the "nonlcon" input.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!