我正在编写一个关于弹丸摩擦力的代码。我认为我犯了一些错误,但我找不到它。它是一个名为targetangle.m的MATLAB函数,它根据发射速度vs,目标距离d和所需精度e计算武器的最佳目标角度θ。
function[ theta dif ] = targetangle(vs,d,e)
% Input the initial condition:
th = 1:0.1:45;
for theta=th
k = 0.2;
g = 9.81;
dt = 0.001;
the = theta * pi/180.;
u(1) = vs * cos(the);
v(1) = vs * sin(the);
% Launch pad location:
x(1) = 0.;
y(1) = 0.;
for t=1:1:6000;
u(t+1) = u(t)- dt * (k * sqrt(u(t)^2+v(t)^2) * u(t));
v(t+1) = v(t)- dt * (k * sqrt(u(t)^2+v(t)^2) * v(t) + g);
x(t+1) = x(t) + u(t) * dt;
y(t+1) = y(t) + v(t) * dt;
% Determination of when the object hits ground:
if y(t+1) < 0
dif = min(abs(x(t+1) - d));
plot(x,y)
end
if y(t+1) < 0;
break
end
end
% Once object hits terminate the computations with a break:
if y(t+1) < 0;
break
end
end
if dif < e
disp(dif)
else
theta = NaN
end
当你这样输入时:
vs = 100;
d = 12;
e = 1;
[ theta dif ] = targetangle(vs,d,e)
输出应为:
theta =
4
dif =
0.0323
但我的代码输出是:
theta =
NaN
theta =
NaN
dif =
3.6718
答案 0 :(得分:1)
计算的问题是,在for循环期间不保存最佳结果。所以你的结果是你上一个循环周期的(非常正确的)结果。
对于θ= 45度,你得到theta = NaN,因为你在最后一个if子句中这样说。 (顺便说一句:缺少分号是你打印两次的原因)
您需要将最佳结果存储在额外的变量中,例如: Theta_opt,dif_opt等:
function[ theta_opt, dif_opt ] = targetangle(vs,d,e)
% Input the initial condition:
th = 1:0.1:45;
k = 0.2;
g = 9.81;
dt = 0.001;
u = 0:.1:599;
v = 0:.1:599;
theta_opt = 1;
dif_opt = 100;
for theta=th
the = theta * pi/180.;
u(1) = vs * cos(the);
v(1) = vs * sin(the);
% Launch pad location:
x(1) = 0.;
y(1) = 0.;
for t=1:1:6000;
u(t+1) = u(t)- dt * (k * sqrt(u(t)^2+v(t)^2) * u(t));
v(t+1) = v(t)- dt * (k * sqrt(u(t)^2+v(t)^2) * v(t) + g);
x(t+1) = x(t) + u(t) * dt;
y(t+1) = y(t) + v(t) * dt;
% Determination of when the object hits ground:
if y(t+1) < 0
dif = min(abs(x(t+1) - d));
if(dif < dif_opt)
theta_opt = theta;
dif_opt = dif;
x_opt = x;
y_opt = y;
end
break
end
% Once object hits terminate the computations with a break:
if y(t+1) < 0;
break
end
end
end
plot(x_opt, y_opt);
if dif_opt < e
disp(dif_opt)
else
theta_opt = NaN;
end