why is my loop printing 0 instead of a value, not sure which part of the code is incorrect

3 ビュー (過去 30 日間)
ERIN
ERIN 2025 年 1 月 27 日
回答済み: charan 2025 年 3 月 10 日
right now the code is at an increment of 15 to test, but the final incremment will be 0.01
code needs to have an if statement within the while loop.
%range is the maximum achievable horizontal distance
% range angle is the angle that yields the maximum horizontaal distance
% use a whilel loop with a nested if statement to compute the maximum
% landing distance (range) ange the angle corrsesponding to the maximum
% landing distance (rangle angle) of the ME En 1010 ping pong cannon
function [range, rangeAngle] = ProjectileRange(d1, d2, v0)
thetaL = 90;
range = 0;
rangeAngle = 0;
[xLand] = LandingDistance(d1, d2, v0, thetaL);
while thetaL <= 90;
if xLand > range
range = xLand
rangeAngle = thetaL
end
thetaL = thetaL + 15;
end
end
%% test
d1 = 0.0876;
d2 = 0.1190;
v0 = 3.2;
[range, rangeAngle] = ProjectileRange(d1, d2, v0);
fprintf('The range is %.2f m at a launch angle of %.2f degrees', range, rangeAngle)
this is what it prints:
The range is 0.00 m at a launch angle of 0.00 degrees>>
I need it to print "the range is 1.29 m at a launch angle of 41.6 degrees" when it has an incrememnt of 0.01
  4 件のコメント
Walter Roberson
Walter Roberson 2025 年 1 月 27 日
plusOrMinus = -1;
[root] = Quadratic(a, b, c, plusOrMinus); % neg root
You ask for the negative root
xLand = x0 + (v0x*tLand);
x0 might not be enough to turn it positive
[xLand] = LandingDistance(d1, d2, v0, thetaL);
if (xLand > range)
xLand might be negative, and so will not be > 0
Cris LaPierre
Cris LaPierre 2025 年 1 月 27 日
Still can't run your code because the code for Quadratic is missing.

サインインしてコメントする。

回答 (1 件)

charan
charan 2025 年 3 月 10 日
Hello Erin,
For the function "LandingDistance" the inputs "d1","d2","v0" are fixed and "thetaL" can vary from 0 to 90. The following code shows the possible values of "xLand".
thetaL=0:1:90;
d1 = 0.0876;
d2 = 0.1190;
v0 = 3.2;
v0x = v0 * cosd(thetaL);
v0y = v0 * sind(thetaL);
x0 = d2*cosd(thetaL);
y0 = d1 + d2*sind(thetaL);
g = 9.81; % gravitational acceleration in m/s^2
a = -0.5*g; % g = acceleration due to gravity in m/s^2
b = v0y; % initial velocity in y direction
c = y0; % initial y position
plusOrMinus = -1;
[root] = roots([a, b, c]); % neg root
tLand = min(root);
xLand = x0 + (v0x*tLand);
plot(thetaL,xLand);
max(xLand)
ans = 0
As seen from the graph the value of "xLand" is always less than or equal to zero. The "range" variable was initialized to zero, so the "if" condition is never satisfied and the execution does not go into the "if" loop. Hence the value of "range" remains zero.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by