MATLAB Answers

fmincon, nonlcon, ode45 - objective output in nonlinear constraint

9 views (last 30 days)
e_frog
e_frog on 20 Dec 2020
Commented: Matt J on 21 Dec 2020
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

Accepted Answer

Matt J
Matt J on 20 Dec 2020
Edited: Matt J on 20 Dec 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
  5 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!