MATLAB: Problem with if else loop

Hi dear, I am trying to model a car accident by analysing skid marks over a track. There is a patch of wet ice present, and the friction coefficient is give. Between 0 to 14 metres, the car is on asphalt, between 14-31m, there is a patch of ice, and 31 to 48 there is still skid marks. I think my model have some issues with executing the if statement after the 14-31m condition. How do i fix this?
for k= 2:length(t)
if s<14
a=-u*g;
u=0.7;
v(k)=v(k-1)+a*dt;
s(k)=s(k-1)+v(k)*dt;
elseif 14<s<31
u=0.12+0.07*exp(0.06*v(k-1));
a=-u*g;
v(k)=v(k-1)+a*dt;
s(k)=s(k-1)+v(k)*dt;
elseif 31<=s
u=0.7;
a=-u*g;
v(k)=v(k-1)+a*dt;
s(k)=s(k-1)+v(k)*dt;
elseif v(k)<0.0
break;
end
end
disp(v);
figure

Best Answer

There are a couple issues I see.
  1. You have too many end keywords. You only need two here.
  2. To test multiple conditions, you have to separate them and as single conditions and join them using & (and) or } (or)
dt=0.01; %change in time increments
g=9.81; %acceleration due to gravity
u=0; %variable u is the kinetic friction constant, for asphalt is 0.7, for ice is 0.07*exp(0.06*v)
% a=-u*g acceleration, calculated from the free body diagram
t=0:dt:10.0;%time in seconds taken for the car to fully stop (v=0)
v=zeros(1,length(t));
s=zeros(1,length(t));
v(1)=25;%velocity
s(1)=0;%displacement
for k= 2:length(t)
if s(k)<14
a=-u*g;
u=0.7;
v(k)=v(k-1)+a*dt;
s(k)=s(k-1)+v(k)*dt;
elseif s(k)>14 & s(k)<31
u=0.12+0.07*exp(0.06*v(k-1));
a=-u*g;
v(k)=v(k-1)+a*dt;
s(k)=s(k-1)+v(k)*dt;
elseif 31<=s(k)
u=0.7;
a=-u*g;
v(k)=v(k-1)+a*dt;
s(k)=s(k-1)+v(k)*dt;
elseif v(k)<0.0
break;
end
end
disp(v);
figure
subplot(2,1,1)
plot(t(1:k),v(1:k));
title('Velocity vs time');
ylabel('Velocity(m/s)');
xlabel('Time(s)');
subplot(2,1,2)
plot(t(1:k),s(1:k));
xlabel('Time(s)');
ylabel('Displacement(m)');
title('Displacement vs time');