# Problem executing if and elseif statements

2 views (last 30 days)
Anurag Dey on 23 Apr 2015
Commented: Anurag Dey on 23 Apr 2015
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')

Michael Haderlein on 23 Apr 2015
You have conditions like
22.22>X(1,i)>11.11
What you actually mean, I guess, is
22.22>X(1,i) && X(1,i)>11.11|
Let's say, X(1,i) is 15. Certainly, you think the result here should be true. But it is false! Why? The first statement will be evaluated from left to right. So, first 22.22>15 is evaluated and results in true. Then the comparison is true>11.11. Obviously, that doesn't work. So, true is converted to 1 and the comparison reads 1>11.11 which of course is false. Not what you intended, I guess.
Second, maybe you should think about the general structure again. It's pretty complicated this way, isn't it? Why not install some current acceleration variable (say, Gcur) which is Gacc at the beginning, is set to Gdec when the velocity is less than 11.11 and is set to Gacc again when the velocity exceeds 22.22? That would be much easier to understand. Just as a hint ;-)

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)
Anurag Dey on 23 Apr 2015
Thanks! It worked!

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