Code about trajectory motion
이전 댓글 표시
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 = abs(x(t+1) - d);
if dif > e;
theta = NaN;
end
min(dif);
plot(x,y);
end
% Once object hits terminate the computations with a break:
if y(t+1) < 0;
break;
end
end
% Graphical presentation of the results:
if y(t+1) > 0;
plot(x,y);
end
end
when you input like this:
>> vs = 100;
>> d = 12;
>> e = 1;
>> [ theta dif ] = targetangle(vs,d,e)
The output should be:
theta =
4
dif =
0.0323
But my code output is :
theta = NaN
dif = 2.2201
답변 (2개)
Walter Roberson
2015년 5월 21일
0 개 추천
When you modify the value of a loop control variable, such as theta, the change is completely overwritten the next time that a loop is started at that level. The change only has lasting effect the last time the loop executes. Whatever it is you are trying to do with setting theta to NaN is almost certainly wrong.
You "break" out of the inner loop when you detect that the ground has been hit. But then no matter distance was on the previous loop, you continue the outer loop, so your final result is going to be the same as if you had only run the final loop iteration. You need to be testing the result inside the outer loop and "break" if you got close enough.
댓글 수: 4
Anson lee
2015년 5월 21일
Walter Roberson
2015년 5월 21일
편집: Walter Roberson
2015년 5월 21일
Example:
goal = 73;
found_solution = false;
for J = 1 : 20
for K = 1 : 35
if J^2 + K^2 == goal
found_solution = true;
end
if found_solution
break
end
end
if found_solution
break
end
end
if found_solution
fprintf('Solved! %d^2 + %d^2 = %d\n', J, K, goal);
else
fprintf('There was no solution');
end
Walter Roberson
2015년 5월 21일
You are breaking out of both loops the first time you hit the ground, not when you determine that you have hit the ground "close enough" to the target. You need to set a flag that is true only if you hit close enough, and you should only exit the outer loop early if the flag is set. You can still exit the inner loop early when you hit the ground.
Torsten
2015년 5월 21일
0 개 추천
Why don't you use ODE45 with the event option ?
Take a look at the paragraph "Event Location" under
Best wishes
Torsten.
카테고리
도움말 센터 및 File Exchange에서 MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!