fmincon, nonlcon, ode45 - objective output in nonlinear constraint
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
Matt J
am 20 Dez. 2020
Bearbeitet: Matt J
am 20 Dez. 2020
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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Optimization finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!