Where is the problem in this if-else structure?

조회 수: 3 (최근 30일)
Riyasat
Riyasat 2016년 8월 28일
댓글: Walter Roberson 2016년 8월 31일
This is an if-else structure of a larger problem. I have simplified it down to the numerals in work here, but can't figure out where lies the problem.
when I evaluate this simple if structure, the program effortlessly outputs a value of "w=1", (The program enters the structure.)
if (1 > 0)&(3 <= 4)
w = 1;
end
But when I evaluate the same above structure inside an if, else if combination the program won't enter in the "elseif structure" for some reason, and only outputs "m=0", whereas I should also get "w=1". What am I doing wrong?
if (4 <= 4)& (3 <= 4)
m= 0;
elseif (1 > 0)&(3 <= 4)
w = 1;
end
Matlab always evaluates:
(4 <= 4)& (3 <= 4)
equals to logical 1. Why won't it then enter inside the if, else-if structure?
  댓글 수: 1
Stephen23
Stephen23 2016년 8월 29일
편집: Stephen23 2016년 8월 29일
"Why won't it then enter inside the if, else-if structure?"
Because that is what it is supposed to do.
"What am I doing wrong?"
You didn't read the if documentation.

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

답변 (2개)

per isakson
per isakson 2016년 8월 28일
편집: per isakson 2016년 8월 30일
"whereas I should also get "w=1"." &nbsp No it should not, because doc says "The statements execute only if previous expressions in the if...end block are false.". In your case a previous expression, (4 <= 4)& (3 <= 4), is true. Only the statements following the first expressions that is true will be executed.

John BG
John BG 2016년 8월 29일
편집: John BG 2016년 8월 29일
because in your
if cond1
elseif cond2
end
cond1 and cond2 are nested, cond2 only happens if cond1 is false. Because in your example cond1 is 1, true, the if exits. It's the way it works.
Try instead
if cond1
..
end;
if cond2
..
end;
or try a switch
if you find this answer useful would you please be so kind to mark my answer as Accepted Answer?
if you would accept my answer with additional comments, please let me know what else you would like to be added in order close your question.
To any other reader, please if you find this answer of any help solving your question,
please click on the thumbs-up vote link,
thanks in advance
John BG
  댓글 수: 3
John BG
John BG 2016년 8월 30일
편집: John BG 2016년 8월 30일
I didn't mention the command switch to do what he expected elseif to do but it doesn't.
I am just encouraging to try a different command, that does the same, hoping for the understanding of the basic point that 'else' implies exclusion, not the expected inclusion that Abdul wonders about.
Guillame, next comment please add something we do not know, cool?
Walter Roberson
Walter Roberson 2016년 8월 31일
Guillame was mentioning something that the original poster probably did not know.

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by