MATLAB Language Conditions IF-ELSE condition


Example

In some cases we want to run an alternative code if the condition is false, for this we use the optional else part:

a = 20;
if a < 10
    disp('a smaller than 10')
else
    disp('a bigger than 10')
end

Here we see that because a is not smaller than 10 the second part of the code, after the else is executed and we get the output a bigger than 10. Now let's look at another try:

a = 10;
if a > 10
    disp('a bigger than 10')
else
    disp('a smaller than 10')
end

In this example shows that we did not checked if a is indeed smaller than 10, and we get a wrong message because the condition only check the expression as it is, and ANY case that does not equals true (a = 10) will cause the second part to be executed.

This type of error is a very common pitfall for both beginners and experienced programmers, especially when conditions become complex, and should be always kept in mind