if else doesn't go through the loop

조회 수: 3 (최근 30일)
Nur
Nur 2014년 2월 13일
댓글: Nur 2014년 2월 13일
Hi,
I have a problem with if else and loop. Lets say I have an array zz double.The value of zz is 2,10,11,23,26,30,37,38,48,53,63,65,66,70,79 and 80. For each element will have its own calculation in the if else statement. I've tried to do if else like this
for Z = 1:numel(zz)
if zz==1;
% if true,do calculation 1
elseif zz==2;
% if true,do calculation 2
and so on.
When I run,it should output result for calculation 2 because the first element in the array is equal to 2. But the coding seems doesn't go through the if else coding. Any help is really appreciated. Thanks.

채택된 답변

Roger Stafford
Roger Stafford 2014년 2월 13일
편집: Roger Stafford 2014년 2월 13일
You have forgotten to index your zz entries in the for-loop. It should read:
for Z = 1:numel(zz)
if zz(Z)==1;
% if true,do calculation 1
elseif zz(Z)==2;
% if true,do calculation 2
Otherwise you are placing an impossible condition on each 'if' or 'elseif'. None of them could ever be true.
  댓글 수: 1
Nur
Nur 2014년 2월 13일
Great! It works.Thanks a lot sir.

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

추가 답변 (2개)

Image Analyst
Image Analyst 2014년 2월 13일
How did you arrive at those numbers? Are you sure they're integers? Did you hard code them in, or are they supposed to be integers because of operations, like 2 = 1.3 + 0.7? If so, that 2 won't equal a int32(2). Read the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F

Nur
Nur 2014년 2월 13일
The numbers are come from my previous coding, as shown below
ActualVelocity=[ActualVelocityP1,ActualVelocityP2..ActualVelocityP82]
zz = find(ActualVelocity>50.000);
Those zz numbers I got from above command.zz will have the ActualVelocity which are >50.00.So number 2,10,11,23,26,30,37,38,48,53,63,65,66,70,79 and 80 represent the location of the value(>50) in the zz array.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by