Use of fmincon with objective function as m-file

4 ビュー (過去 30 日間)
Matthew Hunt
Matthew Hunt 2023 年 1 月 23 日
コメント済み: John D'Errico 2023 年 1 月 23 日
I am finding parameters for a model. I thought the best thing was to define the objective function that I wiah to minimise as
function y=objective_fn(V_exp,V_calc,t)
%This is the objective function
N=length(t); %gets length of vectors
%define the weight of the objective function to concentrate on a particular
So the minimum is where the V_calc is very close to V_exp, which is experimental data we have. Now V_calc is given by:
function V=volt(O_plus,O_minus,X,L_a,L_c,I_app,t)
%Compute the lithium concentration in each of the
%Compute Voltage
To use this objective function, would I need to incorporate them into one big function? The parameters I wish to optimise are contained in the vector X, O_plus/O_minus are fixed rational functions of c_c, and c_a, t is time, I_app, L_a and L_c are constant. I'm a bit confused how to fit these functions into fmincon.


John D'Errico
John D'Errico 2023 年 1 月 23 日
Easy enough. The simple way, assuming all of the variables: {O_plus,O_minus,L_a,L_c,I_app,t} are defined in your workspace, is to create a function handle. So we could do this:
Vcalcfun = @(X) volt(O_plus,O_minus,X,L_a,L_c,I_app,t);
You should see that we can now evaluate this function handle as a function of the only unknown vector X. It will return a vector V, I assume? That should be true from your statements.
Now, your objective function is not how you have written it. The objective to fmincon should have only one unknown (vector) in it.
Why you feel the need to use a weight vector of ALL ones is pretty strange to me. But you can feel free to waste CPU cycles I guess. Your money.
Vobj = @(X) trapz(t,(V_exp.*ones(1,length(t))-Vcalcfun(X)).^2);
Now just call fmincon with Vobj as the objective. EVERYTHING it needs is encapsulated in those two function handles. I assume there is some reason why you want to use fmincon, else you would just be using other tools, perhaps fminunc. So I presume there are equality or inequality constraints between the parameters in X. Again, your choice to write inefficient code otherwise.
  2 件のコメント
John D'Errico
John D'Errico 2023 年 1 月 23 日
How is it more clear to have additional variables that perform no purpose at all? In that case, you should probably define dozens of meaningless variables, serving no purpose at all. But it would make your code more clear?
Whatever floats your boat, I guess. :)


その他の回答 (1 件)

Matt J
Matt J 2023 年 1 月 23 日
編集済み: Matt J 2023 年 1 月 23 日
One way is to wrap the functions in an anonymous function:
fun=@(X) objective_fn(V_exp, volt(O_plus,O_minus,X,L_a,L_c,I_app,t) ,t); %anonymous function




Community Treasure Hunt

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

Start Hunting!

Translated by