# how to use fsolve with multiple variables with unique names, not vectors

6 views (last 30 days)
Entropie_13 on 1 Jan 2022
Commented: Walter Roberson on 3 Jan 2022
Hi,
I want to optimise several variables and give them unique names within the function to optimize, so I have something like this:
fun = @(x1_F, T_WA, T_F)opt(x1_F, T_WA, T_F, alpha_KW, T_D, y1_D, Re_es, nu_gD, rho_gD);
x1_F0 = 0.5; T_WA0 = 345;T_F0 = 355;
T_WAopt = fsolve(fun,x1_F0 T_F0 T_WA0);
I get an error message with this code. Is there away that I can avoid putting all variables into a vector x where I would need to call them in my optimization function opt by x(1),x(2),x(3). This would make my optimization function a bit more difficult to read.

Matt J on 1 Jan 2022
Edited: Matt J on 1 Jan 2022
fun = @(x) opt(x(1), x(2), x(3), alpha_KW, T_D, y1_D, Re_es, nu_gD, rho_gD);
x1_F0 = 0.5; T_WA0 = 345;T_F0 = 355;
xopt = fsolve(fun,[x1_F0 T_F0 T_WA0]);

Matt J on 1 Jan 2022
Edited: Matt J on 1 Jan 2022
This would make my optimization function a bit more difficult to read.
There is no rule that you have to refer to your variables the same way throughout your code..You have the option of unpacking the x(i) into separate variables at the beginning of opt():
function Fval=opt(x, alpha_KW, T_D, y1_D, Re_es, nu_gD, rho_gD)
x1_F=x(1); T_WA=x(2); T_F=x(3);
%More code below
....
Fval=....
end

Alan Weiss on 2 Jan 2022
The Problem-Based Workflow for Solving Equations is designed to do exactly what you want.
Walter Roberson on 3 Jan 2022
s there a possibilty that I can make an output of a variable, which I calculate within the function I use to optimize with fsolve, but which is not part of the variables I want to optimize
Ah, but the output as of which call to your function? Especially when there are constraints, the last call to your function is probably not going to have passed in the same position that was eventually returned to your code. It does happen sometimes, true, but fsolve() typically wants to know if it can get an even better solution, so it is likely to call your function with parameters that come out a bit worse. And if there was in fact no exact solution to your functions and fsolve() is returning the position with minimum error, the final parameters might have been several hundred calls back.
Because of this, most of the time it is better not to even attempt to record all of the values, and instead take the final outputs and use them to calculate what the variable would be. For example you might check nargout and only assign to the output variable if nargout > 1, and then after you get the final inputs, call your opt() function with two outputs . Or if the calculation of the variable is short compared to your fsolve() work, write the calculation into a function that you call from opt() and which you can also call afterwards passing in the optimal parameters (instead of using the nargout idea)