function [x,f,eflag,outpt] = myModelParamsSolver
xLast = [];
myf = [];
myc = [];
myceq = [];
N = 10;
x0 = rand(1,2+2*N);
fun = @objfun;
cfun = @constr;
options = optimoptions('fmincon');
lb = zeros(1,2+2*N);
ub = ones(1,2+2*N);
[x,f,eflag,outpt] = fmincon(fun,x0,[],[],[],[],lb,ub,cfun,options);
function y = objfun(x)
if ~isequal(x,xLast)
[myf,myc,myceq] = myDiscreteTimeModel(x);
xLast = x;
end
y = myf;
end
function [c,ceq] = constr(x)
if ~isequal(x,xLast)
[myf,myc,myceq] = myDiscreteTimeModel(x);
xLast = x;
end
c = myc;
ceq = myceq;
end
function [f,c,ceq] = myDiscreteTimeModel(x)
p = zeros(1,N);
v = p;
u = p;
Ts = 0.01;
p_max = 100;
p_init = 10;
vel_init = 1;
p(1)=p_init;
v(1)=vel_init;
p1 = x(1);
p2 = x(2);
v1 = x(3:3+N-1);
v2 = x(3+N:end);
for n = 1:N
t = N*Ts;
s_star= v1(n) * (v1(n)-v2(n));
p(n+1)= p(n)+ v(n)*t + 0.5*u(n)*t^2;
v(n+1)= v(n)+ u(n)*t;
u(n+1)= (s_star / (p1-p2))^2 ;
end
ceq = v(N);
c = p(N)-p_max;
f = sum(u(:));
end
end
Best Answer