fmincon, nonlcon, ode45 - objective output in nonlinear constraint

조회 수: 4 (최근 30일)
e_frog
e_frog 2020년 12월 20일
댓글: Matt J 2020년 12월 21일
I want to use the output of the objective function in the nonlinear constraint function. My goal is to constrain a solution of an ODE to a specific max value. The Problem with my code is, that I cant seem to pass over the vectors "init_conds_odes" and "tspan_ode" from the objective function (objective) to the nonlinear constraint function (nonlcontest). Those to vectors are not showing up in the workspace of "nonlcontest" if i set a breakpoint as shown in the code. Is the thing I am trying even possible?
Here is the code:
x_0 = init_vars();
init_conds_odes = [1 5 1 1];
lb = x_0 - 0.1;
ub = x_0 + 43;
options = [];
nlcon = @(H,X,tspan_ode,init_conds_odes) nonlcontest(H,X);
[H] = fmincon(@objective,x_0,[],[],[],[],lb,ub,nlcon,options,init_conds_odes);
function [x_0,tmax] = init_vars()
m = 2;
n = 3;
o = 4;
tmin = 0;
tmax = 5;
x_0 = [m;n;o;tmin;tmax];
end
function [obj_val,X,tspan_ode,init_conds_odes] = objective(H,init_conds_odes)
tmin = H(4);
tmax = H(5);
tspan_ode = [tmin tmax];
[t,X] = ode45(@(t,x) ODEs(t,x,H),tspan_ode,init_conds_odes);
dXdt = zeros(length(t),4);
for i = 1:length(t)
[X(i,:),dXdt(i,:)] = ODEs(t,X(i,:),H);
end
z = max(abs(dXdt(:,2)));
obj_val = z;
end
function [X,dXdt] = ODEs(~,X,H)
m = H(1);
n = H(2);
o = H(3);
dXdt = [X(2);
X(1)/m+X(3)/n+9;
X(4);
X(3)/o];
end
function [c,ceq] = nonlcontest(H,~,tspan_ode,init_conds_odes)
% breakpoint here to look at the workspace of nonlcontest. tspan_ode and init_conds_odes are not showing up.
[t,X] = ode45(@(t,x) ODEs(t,x,H),tspan_ode,init_conds_odes);
dXdt = zeros(length(t),4);
for i = 1:length(t)
[X(i,:),dXdt(i,:)] = ODEs(t,X(i,:),H);
end
c = [];
ceq(1) = 0 - X(end,2);
end

채택된 답변

Matt J
Matt J 2020년 12월 20일
편집: Matt J 2020년 12월 20일
You need to get familiar with Passing Extra Parameters - MATLAB & Simulink. Also, fmincon is not appropriate for the max-norm objective. You need to use fminimax instead:
nlcon = @(H) nonlcontest(H,[],tspan_ode,init_conds_odes);
objfun = @(H) objective(H,init_conds_odes);
options = optimoptions('fminimax','AbsoluteMaxObjectiveCount',length(t));
[H] = fminimax(objfun,x_0,[],[],[],[],lb,ub,nlcon,options);
function [obj_val,X,tspan_ode,init_conds_odes] = objective(H,init_conds_odes)
tmin = H(4);
tmax = H(5);
tspan_ode = [tmin tmax];
[t,X] = ode45(@(t,x) ODEs(t,x,H),tspan_ode,init_conds_odes);
dXdt = zeros(length(t),4);
for i = 1:length(t)
[X(i,:),dXdt(i,:)] = ODEs(t,X(i,:),H);
end
objval = dXdt(:,2); %<----- minimize the max-norm of this
end
  댓글 수: 5
e_frog
e_frog 2020년 12월 20일
thanks for the great advice!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Optimization에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by