Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
NCTM or The Math Forum.



Re: Very strange thing when using if else structure
Posted:
Feb 27, 2013 11:59 AM


"Manalap " <mujyhane@gmail.com> wrote in message news:kgl8cs$2o0$1@newscl01ah.mathworks.com... > I encountered a very strange problem when using if else structure. > > Simply put, this problem is like the following. > > If I code > > if x >3 > .... > elseif x<=3 > .... > end > > > then I get a wrong result, but where as if I code > > if x>3 > ... > else > ... > end > > > then I get the correct result that I expected through symbolic reasoning. > > Aren't these two the same thing?
Not if x is nonscalar or x is NaN.
> Can these two be different?
Yes.
x = [1 2 3 4 5]; x > 3 x <= 3
http://www.mathworks.com/help/matlab/ref/if.html
"An evaluated expression is true when the result is nonempty and contains ***all*** nonzero elements (logical or real numeric). Otherwise, the expression is false." [Emphasis added.]
In the first case, neither the IF condition nor the ELSEIF condition are satisfied for the x I gave above, since some elements are greater than 3 and some are less than or equal to 3. In the second case, the IF condition is not true but the ELSE is unconditional; it WILL execute if the IF does not.
 Steve Lord slord@mathworks.com To contact Technical Support use the Contact Us link on http://www.mathworks.com



