2

I used the following simple code to check the properties of elseif command in MATLAB:

x = 10;
if x < 0
   y = x;
elseif 0 <= x < 2
   y = 3*x;
elseif x >= 2
   y = 8*x;
end
y

I would have expected the result of this to be 80 since x >= 2. But something amazing happened! The result is 30, not 80!

But why? Any ideas?

Update: when I change the code (as recommended in the answers) to

x = 10;
if x < 0
   y = x;
elseif (0 <= x) && ( x < 2 )
   y = 3*x;
elseif x >= 2
   y = 8*x;
end
y

I get 80 as expected. It's that double condition that threw me off.

Floris
  • 45,857
  • 6
  • 70
  • 122

2 Answers2

4

When you write

if 0 <= x < 2

you are really writing (without realizing it)

if (0 <= x) < 2

Which is evaluated as

if (true) < 2

which is true, since true evaluates to 1.

So here is what is happening, line by line:

x = 10;            % x is set to 10
if x < 0           % false
   y = x;          % not executed
elseif 0 <= x < 2  % condition is (true) < 2, thus true
   y = 3*x;        % y is set to 3*x, i.e. 30
elseif x >= 2      % since we already passed a condition, this is not evaluated
   y = 8*x;        % skipped
end                % end of composite if 
y                  % display the value of y - it should be 30

As an aside, when you use scalars, you should really use the && operator, not the & operator. See for example What's the difference between & and && in MATLAB?

Community
  • 1
  • 1
Floris
  • 45,857
  • 6
  • 70
  • 122
2

0 <= x < 2 doesn't behave as you may expect. Use (0 <= x) & (x < 2)

How does 0 <= x < 2 behave? It is evaluated from left to right. First 0 <= x gives 1 (true), and then 1 < 2 gives 1 (true). So the condition gives true, not false as you would expect.

Since the second condition in your code (0 <= x < 2) is true, you get a value 30 for y. Changing the condition to (0 <= x) & (x < 2) you get a value 80 for y.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147