Problem executing if and elseif statements

2 visualizzazioni (ultimi 30 giorni)
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;
if X(1,i)>=22.22
elseif 22.22>X(1,i)>11.11 && X(1,i)<X(1,i-1)
elseif 22.22>X(1,i)>11.11 && X(1,i-1)<X(1,i)
elseif X(1,i)<=11.11
plot(X(2,:),X(1,:)) grid xlabel('Time(s)') ylabel('velocity')

Risposta accettata

Michael Haderlein
Michael Haderlein il 23 Apr 2015
You have conditions like
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 ;-)

Più risposte (2)

Julia il 23 Apr 2015
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)
22.22>X(1,i) && X(1,i)>11.11 && X(1,i-1)<X(1,i)

Titus Edelhofer
Titus Edelhofer il 23 Apr 2015
in MATLAB you cannot use chains of inequality: you need to replace
22.22>X(1,i) && X(1,i)>11.11


Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by