MATLAB: In an assignment A(:) = B, the number of elements in A and B must be the same. Error whle using fmincon

fmincon

I'm trying to optimize the objective function
function f = Objfun(u,x0)
[T,X] = ode45(@(t,x)eqs(t,x,u), [0 132], x0);
f = -X(end,2)*X(end,4);
end
The optimization is using fmincon and is shown below
clc; close all; clear ;
X1 = [1.5 0 0 7];
lb = 0;
ub = 50;
[x, fval] = fmincon(@(u)Objfun(u, X1), 11.25, [],[],[],[], lb,ub,@(u)nonlincon(u,X1));
The function for the nonlinear constraint is:
function [c,ceq] = nonlincon(u,x0)
[T,x] = ode45(@(t,x)eqs(t,x,u), [0 132], x0);
c = [];
c(:,1) = -x(:,1);
c(:,2) = x(:,1) - 10;
c(:,3) = -x(:,3);
c(:,4) = x(:,3) - 25;
c(:,5) = -x(:,4);
c(:,6) = x(:,4) - 10;
ceq = [];
end
The error I'm getting is as below:
In an assignment A(:) = B, the number of elements in A and B must be the same.
Error in barrier (line 402)
Error in fmincon (line 818)
[X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN] = barrier(funfcn,X,A,B,Aeq,Beq,l,u,confcn,options.HessFcn, ...
Error in SolveUwoBound (line 6)
[x, fval] = fmincon(@(u)Objfun(u, X1), 11.25, [],[],[],[], lb,ub,@(u)nonlincon(u,X1));
What is the problem here?

Best Answer

I think, but am not 100% certain, that the reason you are getting an error is that ode45 gives a variable number of output times when called using the two-element tspan, which you give as [0 132]. I suggest that you give a vector with more elements in tspan, and see if that helps.
It also looks as if you are trying to keep the solution x(t) within bounds for all t. I am not sure how well that will work. You almost certainly want more elements in tspan to keep at least the solution at those points within the bounds. I suggest that you check the documentation on optimizing a simulation or ODE for some caveats and hints.
Alan Weiss
MATLAB mathematical toolbox documentation