function [x,f,eflag,outpt] = ans_324101
xLast = [];
myf = [];
myc = [];
myceq = [];
x_pts = [];
y_pts = [];
fun = @objfun;
cfun = @constr;
options = optimoptions('fmincon','MaxFunctionEvaluations',500,...
'PlotFcn',@optimplotfval,'OutputFcn',@outfun);
x0 = [10 deg2rad(30) 1];
x_0 = 0;
y_0 = 0;
y_threshold = 3;
x_threshold = 3;
figure;
hopt = plot(0,0);
hold on;
plot([x_0+x_threshold; x_0+x_threshold],[y_0; y_0 + y_threshold*1.5],'r');
plot([x_0; x_threshold*1.5],[y_0 + y_threshold; y_0 + y_threshold],'r');
axis([0 x_threshold*1.5 0 y_threshold*1.5]);
lb = [0 0 0];
ub = [10 deg2rad(90) 10];
[x,f,eflag,outpt] = fmincon(fun,x0,[],[],[],[],lb,ub,cfun,options);
function y = objfun(x)
if ~isequal(x,xLast)
[myf,myc,myceq,~,x_tmp,y_tmp] = myModel(x);
xLast = x;
x_pts = x_tmp;
y_pts = y_tmp;
end
y = myf;
end
function [c,ceq] = constr(x)
if ~isequal(x,xLast)
[myf,myc,myceq,~,x_pts,y_pts] = myModel(x);
xLast = x;
end
c = myc;
ceq = myceq;
end
function [f,c,ceq,t,x_pts,y_pts] = myModel(x)
v_0 = x(1);
theta = x(2);
m = x(3);
t = 0:0.01:5;
k = 0.5;
g = 9.8;
x_pts = m*v_0/k*(1-exp(-k/m*t))*cos(theta)+x_0;
y_pts = -m/k*((v_0*sin(theta) + m/k*g)*(exp(-k/m*t)-1)+g*t)+y_0;
[~,idxMaxY] = max(y_pts);
c(1) = -y_pts(idxMaxY)+ y_threshold;
[~,idxYZero] = min(abs(y_pts(idxMaxY+1:end)));
c(2) = -x_pts(idxMaxY+idxYZero) + x_threshold;
f = m;
ceq = [];
end
function stop = outfun(~,~,~)
stop = false;
set(hopt,{'XData','YData'},{x_pts,y_pts});
end
fprintf('v0=%f[m/s], theta=%f[deg], m=%f[kg]\n',x(1),rad2deg(x(2)),x(3));
end