Fmincon objective and nlcon shared simulink parameters

I'm trying to minimize a function of my vector X which is the input of my simulink model.
Right now i'm doing:
X=fmincon(@(X)objective,x0,A,B,Aeq,Beq,@(X)nonlcon,options)
function [f,gradf]=objective(X,simulation_param,Tfinal)
T=(0:1:Tfinal)';
TIN=[T X]
[~,~,yout]=sim('sim_model',[0 Tfinal],opt ,TIN);
f=some_fun_of(yout)
gradf=some_other_fun_of(yout)
end
function [G,P,gradG,gradP]=nonlcon(X,simulation_param,Tfinal)
T=(0:1:Tfinal)';
TIN=[T X]
[~,~,yout]=sim('sim_model',[0 Tfinal],opt ,TIN);
G=constr_fun_of(yout)
gradG=some_other_constr_fun_of(yout)
P=...
gradP=...
end
Since the simulation is the same, i would like fmincon to call it only once and not twice (once for objective fun and once for nonlcon fun).
but i dont know how to readapt the code if i have a Simulink simulation.

 採用された回答

Matt J
Matt J 2020 年 10 月 31 日
編集済み: Matt J 2020 年 10 月 31 日

0 投票

function [x,f,eflag,outpt] = runobjconstr(x0,opts)
if nargin == 1 % No options supplied
opts = [];
end
simulation_param=...,
Tfinal=...,
xLast = []; % Last place update_yout was called
yout=[];
fun = @objfun; % The objective function, nested below
cfun = @constr; % The constraint function, nested below
% Call fmincon
[x,f,eflag,outpt] = fmincon(fun,x0,[],[],[],[],[],[],cfun,opts);
function [f,gradf] = objfun(x)
if ~isequal(x,xLast) % Check if computation is necessary
update_yout(x);
xLast = x;
end
% Now compute objective function
f=some_fun_of(yout)
gradf=some_other_fun_of(yout)
end
function [G,P,gradG,gradP] = constr(x)
if ~isequal(x,xLast) % Check if computation is necessary
update_yout(x);
xLast = x;
end
G=constr_fun_of(yout)
gradG=some_other_constr_fun_of(yout)
P=...,
gradP=...,
end
function update_yout(X)
T=(0:1:Tfinal)';
TIN=[T X]
[~,~,yout]=sim('sim_model',[0 Tfinal],opt ,TIN);
end
end

6 件のコメント

Alberto Belvedere
Alberto Belvedere 2020 年 11 月 1 日
Thank you for your help!
If i want to provide also the hessian, that is a function of yout, to fmincon, can i proceed in the same way?
Matt J
Matt J 2020 年 11 月 1 日
Yes, you can do anything with yout
Alberto Belvedere
Alberto Belvedere 2020 年 11 月 1 日
Since the hessian get passed through options i just make it point to a function that is nested? Like:
function runobjconstr(...)
options=optimoptions('fmincon',... ,'HessFcn', @nested_fun)
.
.
.
function hess=nested_fun(x,lambda)
end
end
Matt J
Matt J 2020 年 11 月 1 日
編集済み: Matt J 2020 年 11 月 1 日
Yes, all functions nested within runobjconstr will have shared access to yout.
Alberto Belvedere
Alberto Belvedere 2020 年 11 月 1 日
Thanks, i mark this as closed
Farshid R
Farshid R 2022 年 9 月 26 日
Hello,
Could I ask a question about optimization?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeNonlinear Optimization についてさらに検索

質問済み:

2020 年 10 月 31 日

コメント済み:

2022 年 9 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by