next up previous contents
Next: 6.3 Modular programming Up: 6. Real programming Previous: 6.1 Loops   Contents

6.2 Branching

In the expressions that determined the exit condition for our while loops in the preceding section, we used logic elements (>= and >) to compare two values. We'll also need to use logic elements in branching constructs, so we'll list them all here in Table 6.1. Technically speaking there are two types of logic elements, relational operators and logical operators, but we won't worry about those distinctions here.

Table 6.1: Logic elements in MATLAB used for comparing values and branching.
Relational operators Description
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal to (Don't confuse with
  the assignment operator =)
$\sim$= Not equal to
Logic operators Description
& AND
| OR
$\sim$ NOT

The purpose of branching in computer programming is to execute different commands for different conditions. For example, consider the code below
% First example of branching
clear all; close all; clc;
for nums = 1:10 % Loop over all integers 1 thru 10 (by 1's)
    remainder = mod(nums,2); % Calculate the remainder of nums/2
    numstr = num2str(nums);  % Convert the value of 'nums' into a string
                             % so it can be printed
    if remainder == 0        % Note the use of a DOUBLE equal sign
        disp([numstr ' is even'])  % do this only if the remainder is zero
    else
        disp([numstr ' is odd'])   % do this whenever remainder is NOT zero
    end % Every if-else block requires an end statement
end % This end statement marks the end end of the for loop
In this example, the remainder of $x/2$ is calculated for all integers $1\leq x \leq 10$. If the remainder is zero, then we know that the integer $x$ is even. The remainder is calculated with the mod function. The if statement checks to see if the remainder is zero. If the condition is true, the program branches to the first statement in the if-else block and prints the value of the number and the words ``is even''. On the other hand, if the condition is false (if the remainder is not equal to zero), then the first branch of the if-else block is skipped and program execution proceeds to the else statement. When the else statement is executed, the statements in its block are always executed. So, if the value of the variable remainder is not zero, then the first branch of the if-else statements will be skipped and the second block (the else block) will be executed. Every if statement needs a corresponding end statement to indicate the end of the branching blocks. An if statement can be used alone without an else branch. Look at this small variation of the preceding example. A second if statement has been added that checks to see if an even number is also divisible by 4. This example also shows how if blocks can be nested one inside the other.
% First example of branching
clear all; close all; clc;
for nums = 1:10 % Loop over all integers 1 thru 10 (by 1's)
    remainder = mod(nums,2); % Calculate the remainder of nums/2
    numstr = num2str(nums);  % Convert the value of 'nums' into a string
                             % so it can be printed
    if remainder == 0        % Note the use of a DOUBLE equal sign
        disp([numstr ' is even'])  % Do this only if the remainder is zero
        if mod(nums,4) == 0  % See if nums/4 also has a zero remainder
            disp('It is also divisible by 4')
        end
    else
        disp([numstr ' is odd'])   % Do this whenever remainder is NOT zero
    end % Every if-else block requires an end statement
end % This end statement marks the end of the for loop

One more branching construct you should be familiar with is elseif. These constructs are used in conjunction with an if statement. Suppose we have scores from a test and we want to assign letter grades based on the scores. If a score is 90% or above, we will assign an A; otherwise if the score is 80% or above, we will assign a B; etc. The following program illustrates how if-elseif blocks can be used to assign the scores. Note that only one of the blocks will be executed in each case--once one block has been executed all of the others will be skipped without checking if the conditional expressions are true or false.
% Example of elseif blocks
clc; clear all; close all; % clean up command window, memory, and desktop
scores = 15*randn(10,1)+75 % generate 10 bell curve scores; avg 75; sigma 15
for i = 1:length(scores)   % length(scores) returns the number of elements in 'scores' 
    if scores(i) >= 90
        disp('A')
    elseif scores(i) >= 80
        disp('B')
    elseif scores(i) >= 70
        disp('C')
    elseif scores(i) >= 60
        disp('D')
    else
        disp('F')
    end
end
Using logical operators (see Table 6.1), we can also check for multiple conditions. Let's change our first example from this section to run over all the integers $-5$ to 5. We'll assume that we only want to call an integer even if it is divisible by 2 and it is not zero.
% Example of checking multiple conditions 
clear all; close all; clc;
for nums = -5:5 
    remainder = mod(nums,2); 
    numstr = num2str(nums);  
    if (remainder == 0 & nums ~= 0) % Check for the truth of BOTH conditions
        disp([numstr ' is even'])  
    elseif remainder ~=0            % Check for non-zero remainder
        disp([numstr ' is odd'])   
    end 
end
We made two changes to the original script. The condition of the if statement now includes two conditions with the ``and'' operator & between them. The statement block of the if statement is executed only if both of the conditions are true. Carefully note that we were forced to make a second change as well. The original else statement was changed to an elseif statement with a condition testing the value of remainder for a non-zero result. Without this change, the program will print ``0 is negative.'' Why? What happens when remainder is zero and the value of nums is also zero? Explain your answer to the instructor before going on.
next up previous contents
Next: 6.3 Modular programming Up: 6. Real programming Previous: 6.1 Loops   Contents
Gus Hart 2005-01-28