MATLAB: My code is just about there, but there is something not right…I can’t figure it out. Help?!

for loopif statementphysics

Here's my code:
if true
% code
end
m=1428.8;
a_i=3;
b=1.04;
MaxSpeed= 65 * .4474;
SpeedLimit= 50 * .4474;
t=[0:.5:50];
a= NaN(length(t),1);
v= NaN(length(t),1);
x= NaN(length(t),1);
a(1)=a_i;
v(1)=0;
x(1)=0;
for k = 2:length(t)
v(k)= a.*t;
%a)
if v(k)==min(v(k),MaxSpeed);
a=0;
x(k)=v*t(k);
end
%b)
if x(k-1)<275
a(k)=(b*(v(k-1)).^2)/(2*m);
x(k)=(MaxSpeed*t)+ (.5*a(k)*(t(k)^2));
end
%c)
if x==1000
if v(k)>SpeedLimit
disp('keep coasting');
v(k)
end
end
end
subplot(1,3, 1);
plot(t, x);
xlabel('time(s)');
ylabel('distance(m)');
subplot(1,3, 2);
plot(t, v);
xlabel('time(s)');
ylabel('velocity(m/s)');
subplot(1,3, 3);
plot(t, a);
xlabel('time(s)');
ylabel('acceleration');

Best Answer

I am pretty sure this is the correct code now. As for the sum(x>1000), the answer was 44. Is that the number of time steps it took for x to become greater than 1000? Here's the code:
m=1428.8;%mass of car
a_i=3;%initial acceleration
b=1.04;%constant
MaxSpeed= 65 * .4474;%mph - m/s

SpeedLimit= 50 * .4474;%mph - m/s
dt=.5;%time step
t=[0:dt:50];%time
N=length(t);%legthg of time
a= NaN(1,length(t));%empty acceleration vector
v= NaN(1,length(t));%empty velocity vector
x= NaN(1,length(t));%empty position vector
a(1)=a_i;%initial acceleration = 3
v(1)=0;%initial velocity = 0
x(1)=0;%initial position =0
for k=2:N
F_drag=.5*b*((v(k-1))^2);%drag force
a(k)=a(k-1)-(F_drag/m);%net acceleration
v(k)= v(k-1)+ ((a(k)+a(k-1))/2)*dt;%velocity
x(k)=x(k-1)+ dt*((v(k)+v(k-1)/2));%position
%a)
if x(k)>150%when acceleration should equal zero
a(k)=0;%acceleration = 0
v(k)=MaxSpeed;%velocity equals max speed
x(k)=x(k-1)+ dt*((v(k)+v(k-1)/2));
end
%b)
if x(k-1)>275%when you pass the 50mph speed limit sign
a(k)=-(F_drag/m);%acceleraton from the car is zero and the drag force is decelerating the car
v(k)= v(k-1)+ ((a(k)+a(k-1))/2)*dt;%new velocity
end
end
%c)
if x(k-1)>1000 && v(k)<=SpeedLimit %when you pass the police car
disp('keep coasting');%if the velocity os less than or equal to the speed limit
v(k);
speed=v(k)/.4474;
disp('speed in mph');
speed%displays velocity right after you pass the police car
else
disp('pull over');%if velocity is greater than the speed limit
v(k);
speed=v(k)/.4474;
speed
end
figure;%plots
subplot(3,1, 1)
plot(t, x)%time vs. position plot
xlabel('time(s)');
ylabel('position(m)');
subplot(3,1, 2)
plot(t, v)%time vs. velocity
xlabel('time(s)');
ylabel('velocity(m/s)');
subplot(3,1, 3)
plot(t, a)%time vs. acceleration plot
xlabel('time(s)');
ylabel('acceleration');