Problem executing if and elseif statements

조회 수: 3 (최근 30일)
Anurag Dey 2015년 4월 23일
댓글: Anurag Dey 2015년 4월 23일
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')

댓글을 달려면 로그인하십시오.

채택된 답변

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 ;-)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Julia 2015년 4월 23일
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이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Anurag Dey 2015년 4월 23일
Thanks! It worked!

댓글을 달려면 로그인하십시오.

Titus Edelhofer 2015년 4월 23일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by