5 views (last 30 days)

Show older comments

Hi i am trying to minimize some output of a system of 2 ODEs that also are bound by a nonlinear constraint. Unfortunately I cant seem to get my syntax for implementing the nonlcon right.

To clarify what I want to achieve with the nonlnear constraint: The last value of X(2) (a velocity) has to be zero.

I know this is a fairly common question on here, but the other questions and answers couldn't solve my problem. This is my specific code:

x_0 = init_vars();

init_conds_odes = [1 0 5 0];

lb = x_0 - 54;

ub = x_0 + 43;

options = [];

nlcon = @nonlcon;

[H] = fmincon(@objective,x_0,[],[],[],[],lb,ub,@nonlcon,options,init_conds_odes);

These are the functions:

function [x_0,tmax] = init_vars()

m = 2;

n = 3;

o = 4;

tmax = 5;

x_0 = [m;n;o;tmax];

end

function [obj_val,X] = objective(H,init_conds_odes)

tmax = H(4);

tspan_ode = [0 tmax];

[~,X] = ode45(@(t,x) ODEs(t,x,H),tspan_ode,init_conds_odes);

z = max(abs(X(:,2)));

obj_val = z;

end

function [dXdt] = ODEs(~,X,H)

m = H(1);

n = H(2);

o = H(3);

dXdt = [X(2);

X(1)/m+X(3)/n+1;

X(4);

X(3)/o];

end

function [c,ceq] = nonlcon(X)

c = [];

ceq(1) = 0 - X(end,2);

end

This is the error message:

Error using test>nonlcon

Too many input arguments.

Error in fmincon (line 639)

[ctmp,ceqtmp] = feval(confcn{3},X,varargin{:});

Error in test (line 13)

[H] = fmincon(@objective,x_0,[],[],[],[],lb,ub,@nonlcon,options,init_conds_odes);

Caused by:

Failure in initial nonlinear constraint function evaluation. FMINCON cannot continue.

Walter Roberson
on 17 Dec 2020

nonlcon will be passed t and x. You are not required to make use of t, but it will be passed.

function [c,ceq] = nonlcon(~, X)

Walter Roberson
on 20 Dec 2020

If those initial conditions must be met, then specify them as part of the boundaries.

Remember that if needed you can add an extra variable to act as an extra layer of differentiation or an extra layer of integration (as needed) in order to be able to put boundary conditions on derivatives or positions.

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

Start Hunting!