MATLAB: Help with finding the minimum and maximum angle of a trajectory.

physicstrajectory

Hello. I am having trouble with solving the first program of my physics course. We have this code, that calculates the trajectory of a projectile with air resistance based on a given angle a0:
What I need to do is, I have to modify it. I need to input a distance and have the program calculate the minimum and maximim angle from which I can shoot the projectile so that it hits the distance that I entered.
Edit by Image Analyst: Adrian's code from pastebin pasted below:
% Lab 2
% Traictoria balistica cu frecare patratica in viteza (Ballistic trajectory with air resistance <and something that i can't translate>
clear all; clear all; clc;
g=9.80665; %m/s
m=1; %kg
v0=1000;
a0=39*pi/180; %the angle of "shooting" the projectile
r1=m*g/2/v0;
r2=m*g/3/v0^2;
t0=0;
tfe=2*v0*sin(a0)/g;
N=1000;
dt=(tfe-t0)/(N-1);
t=t0:dt:tfe;
vx=zeros(1,N);
vy=zeros(1,N);
x=zeros(1,N);
y=zeros(1,N);
vx(1)=v0*cos(a0);
vy(1)=v0*sin(a0);
for i=1:N-1
E=1-dt/m*(r1+r2*sqrt(vx(i)^2+vy(i)^2));
vx(i+1)=vx(i)*E;
vy(i+1)=vy(i)*E-g*dt;
x(i+1)=x(i)+dt*vx(i);
y(i+1)=y(i)+dt*vy(i);
if(y(i+1)<0);
j=i;
break;
end;
end;
t=t(1:j);
x=x(1:j);
y=y(1:j);
figure(1);
plot(x,y,'-b','LineWidth',2);
b=round(x(j));
tf=round(t(j));
disp(b);
disp(tf);

Best Answer

The easiest thing to do might be to put the whole thing in a loop over angle. Go from angle 1 to 90 in steps of 1 degree or something. Then save the distance as x(end). Something like
angles = linspace(1, 90, 1);
for k = 1 : length(angles)
a0 = angles(k) * pi / 180; %the angle of "shooting" the projectile in radians
% More (existing) code to compute x and y, etc.
% Save the distance it went.
distances(k) = x(end);
end
Then use min() to find the distance closest to the inputted distance, and from that extract the angle you should use.
[minDeltaDistance, indexOfMin] = min(distances - desiredDistance);
desiredAngle = angles(indexOfMin); % Angle that will give you the closest distance.
actualDistance = **** you do this ******* ; % The actual distance that it went.
For more accuracy, use more elements in linspace().
This is one way, anyway.