Problem executing if and elseif statements
Show older comments
Hello all,
Here is my problem statement:
I have a car that is moving at 80 kmph (22.22 mps) . I apply the brakes and decelerate it to 40 kmph. As soon as my car reaches to 40 kmph i want it to accelerate it back to 80 kmph and continue the process of acceleration and deceleration between 80kmph and 40 kmph for the next 60 next seconds at an interval of 0.1 seconds. I have written the following code but cannot figure out why the graph is not bouncing between 22.22 and 11.11 at intervals of 0.1 seconds. Everything looks fine from my point of view.
n=2; Tstep=0.1; Tfinal=60; X= zeros (n,Tfinal/Tstep); X(1,1)=22.22; Gdec=-1.5; Gacc=0.5;
for t=0:0.1:60;
i=round((t*10)+1);
X(2,i)=t;
if X(1,i)>=22.22
X(1,i+1)=X(1,i)+Gdec*Tstep;
elseif 22.22>X(1,i)>11.11 && X(1,i)<X(1,i-1)
X(1,i+1)=X(1,i)+Gdec*Tstep;
elseif 22.22>X(1,i)>11.11 && X(1,i-1)<X(1,i)
X(1,i+1)=X(1,i)+Gacc*Tstep;
elseif X(1,i)<=11.11
X(1,i+1)=X(1,i)+Gacc*Tstep;
end
end
plot(X(2,:),X(1,:)) grid xlabel('Time(s)') ylabel('velocity')
Accepted Answer
More Answers (2)
Julia
on 23 Apr 2015
Hi,
your first two elseif-statements should be changed to:
22.22>X(1,i) && X(1,i)>11.11 && X(1,i)<X(1,i-1)
and
22.22>X(1,i) && X(1,i)>11.11 && X(1,i-1)<X(1,i)
1 Comment
Anurag Dey
on 23 Apr 2015
Titus Edelhofer
on 23 Apr 2015
Hi,
in MATLAB you cannot use chains of inequality: you need to replace
22.22>X(1,i)>11.11
by
22.22>X(1,i) && X(1,i)>11.11
Titus
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!