MATLAB: Projectile motion with drag and magnus effect. So far im just trying to make it work with air resistance however I get a Index exceeds the number of array elements (1). Error in projectile_golf (line 36) vx(i)=vx(i​-1)-FdragX​(i-1)*dt;

mechanical engineeringprojectile motion

function projectile_golf
clear
clc
format long g;
workspace
format compact
fontSize = 20;
g = 9.81; % acceleration due to gravity in Y
y0 = 0; % intial position y
v0 = 50; % initial velocity magnitude
Angular_w = 100 % Angular Velocity (rad/s)
angle = 30; % angle of strike
c = 4.5*10^(-5); % Coefficient of drag
r = 21.5*10^(-3); % Radius of gold ball
m = 46*10^(-2); % Mass of golf ball
rho_air = 1.2; % Density of air
px(1) = 0; % position of x initial
py(1) = y0; % position of y initial
v(1) = v0;
vx = v0*cosd(angle);
vy = v0*sind(angle);
vx(1) = vx;
vy(1) = vy;
dt=0.1;
t=[0:dt:100];
FdragX(1) = v(1)*vx(1)*c; % Drag force in X direction
FdragY(1) = v(1)*vy(1)*c; % Drag force in Y direction
for i=2:length(t)
v(i) = sqrt((vx(i-1)^2)+(vy(i-1)^2)); % velocity magnitude
px(i)=px(i-1)+vx(i-1)*dt; % new position x
vx(i)=vx(i-1)-FdragX(i-1)*dt; % new velocity x

py(i)=py(i-1)+vy(i-1)*dt; % new position y
vy(i)=vy(i-1)-g*dt-FdragY(i-1)*dt; % new velocity x
if py<0
i = length(t);
end
end
figure(1);
plot(px,py);

Best Answer

You don't update FdragX and FdragY. You should add
FdragX(i) = v(i)*vx(i)*c; % Drag force in X direction
FdragY(i) = v(i)*vy(i)*c; % Drag force in Y direction
inside you loop.
Also, instead of trying to alter i within the loop, you might be better to use
if py(i)<0
break
end