# Where is the problem in this if-else structure?

18 views (last 30 days)
Riyasat on 28 Aug 2016
Commented: Walter Roberson on 31 Aug 2016
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?
Stephen on 29 Aug 2016
"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.

per isakson on 28 Aug 2016
Edited: per isakson on 30 Aug 2016
"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 on 29 Aug 2016
Edited: John BG on 29 Aug 2016
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.
if cond1
..
end;
if cond2
..
end;
or try a switch
John BG
Walter Roberson on 31 Aug 2016
Guillame was mentioning something that the original poster probably did not know.