MATLAB Language Conditions Nested conditions


When we use a condition within another condition we say the conditions are "nested". One special case of nested conditions is given by the elseif option, but there are numerous other ways to use nested conditons. Let's examine the following code:

a = 2;
if mod(a,2)==0    % MOD - modulo operation, return the remainder after division of 'a' by 2
    disp('a is even')
    if mod(a,3)==0
        disp('3 is a divisor of a')
        if mod(a,5)==0
            disp('5 is a divisor of a')
    disp('a is odd')

For a=2, the output will be a is even, which is correct. For a=3, the output will be a is odd, which is also correct, but misses the check if 3 is a divisor of a. This is because the conditions are nested, so only if the first is true, than we move to the inner one, and if a is odd, none of the inner conditions are even checked. This is somewhat opposite to the use of elseif where only if the first condition is false than we check the next one. What about checking the division by 5? only a number that has 6 as a divisor (both 2 and 3) will be checked for the division by 5, and we can test and see that for a=30 the output is:

a is even
3 is a divisor of a
5 is a divisor of a

We should also notice two things:

  1. The position of the end in the right place for each if is crucial for the set of conditions to work as expected, so indentation is more than a good recommendation here.
  2. The position of the else statement is also crucial, because we need to know in which if (and there could be several of them) we want to do something in case the expression if false.

Let's look at another example:

for a = 5:10    % the FOR loop execute all the code within it for every a from 5 to 10
    ch = num2str(a);    % NUM2STR converts the integer a to a character
    if mod(a,2)==0
        if mod(a,3)==0
            disp(['3 is a divisor of ' ch])
        elseif  mod(a,4)==0
            disp(['4 is a divisor of ' ch])
            disp([ch ' is even'])
    elseif mod(a,3)==0
        disp(['3 is a divisor of ' ch])
        disp([ch ' is odd'])

And the output will be:

5 is odd
3 is a divisor of 6
7 is odd
4 is a divisor of 8
3 is a divisor of 9
10 is even

we see that we got only 6 lines for 6 numbers, because the conditions are nested in a way that ensure only one print per number, and also (although can't be seen directly from the output) no extra checks are preformed, so if a number is not even there is no point to check if 4 is one of it divisors.