Help with plotting projectile motion with a for loop

조회 수: 17 (최근 30일)
James Finch
James Finch 2016년 7월 16일
댓글: Walter Roberson 2016년 7월 17일
Hey guys,
I've been working on this script for the past two days and I've hit a wall. What needs to happen, is the user inputs various data then it spits out a graph with the projectile trajectory. I'm very new to any kind of coding, and any and all help is appreciated.
Here's the code:
close all; clear all; clc;
theta1 = input('What is the desired launch angle in degrees? ' );
theta = rad2deg(theta1);
x0 = input('What is the initial horizonal position in meters? ');
y0 = input('What is the initial vertical position in meters? ');
v0 = input('What is the initial launch velocity in m/sec? ');
%m = input('What is the mass of the object in kg? ');
g = -input('What is the desired acceleration due to gravity? ');
xmax = ((v0.^2).*sin(2.*(theta)./g));
ymax = ((v0.^2).*(sin(theta).^2))./g;
time1 = ((2.*v0.*sin(theta))./g);
time2 = ['Amount of time in flight: ', num2str(time1)];
xmax1 = ['Distance the object traveled: ', num2str(xmax)];
ymax1 = ['Maximum height reached: ', num2str(ymax)];
t = 0 : .01 :500;
angles = length(theta);
for k = 1 : angles;
%angle = theta(k);
xvelo = v0 * cos(theta);
yvelo = v0 * sin(theta);
x = xvelo .* t + (1/2) * x0 .* t.^2;
y = yvelo .* t + (1/2) * g .* t.^2;
plot(x, y, 'Linewidth', 1.5);
grid on;
end
disp(time2);
disp(xmax1);
disp(ymax1);
disp(theta);

답변 (1개)

Walter Roberson
Walter Roberson 2016년 7월 16일
theta = rad2deg(theta1);
is the wrong way around: your prompt is in degrees, so if you are going to convert at all it should be deg2rad() . If you decide to leave it in degrees then use sind() and cosd() instead of sin() and cos()
  댓글 수: 2
James Finch
James Finch 2016년 7월 16일
Thank you! That's definitely helpful. I'm having a hard time with the loop working correctly as well.
Walter Roberson
Walter Roberson 2016년 7월 17일
The wording of your prompt implies that the user is expected to input a single degree angle, but your loop is over the number of degree angles input. If you are expecting the user to input multiple angles then you should change the prompt.
If the user does input multiple angles, then do you want all of the trajectories to appear on the same graph? If so then you will need to add a
hold on
after the first plot()

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Assembly에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by