Examples

  1. The example uses the randperm() function to simulate rolling a pair of dice. The randperm() function takes a positive integer N and returns a vector containing the values from 1 to N in a random order. In other words, randperm(N) returns a random permutation of the values from 1 to N. You can see for yourself how randperm() works by running the command randperm(6). We introduce this function so that it can be used to simulate random events. Conditional expressions can use the results of this to choose a path of execution.
        >> results = randperm(6)
    
        results =
    
             2     4     3     6     5     1
    
        >> 

    It is common to use only the first value of a call to the randperm() function.

        >> results(1)
    
        ans =
    
             2
    
        >> 

    Notice how each value is value from 1 to 6 is only found once. To simulate independent rolls of a die, one must call randperm to generate new values for each roll.

  2. This nested code fragment will display "Congratulations, you rolled doubles!" if the results of two calls of randperm(6) return the same value in the first position. Then, if double were rolled, it will test for Snake Eyes or Box Cars.

        roll1 = randperm(6);
        roll2 = randperm(6);
    
        die1 = roll1(1);
        die2 = roll2(1);
    
        if ( die1 == die2 )
            disp('Congratulations, you rolled doubles!');
            if ( die1 + die2 == 2 )
               disp('Double ones is also known as Snake Eyes');
            elseif ( die1 + die2 == 12 )
               disp('Double sixes is also known as Box Cars');
            end
        else 
            disp('Sorry, no doubles!');
        end
    

    Here is the control flow diagram for this code fragment.

    Control flow chart with three nested if statements.
  3. The complex boolean expression in the previous lesson's exercise can be made easier to understand and debug by choosing the following operators and using nested if statements.
    if (temp1 > 32 & temp1 < 212) 
        if (temp2 > 32 & temp2 < 212)
            disp('H20 is water at both ',num2str(temp1), ' and ', num2str(temp2));
        end
    end
    

    It is often preferrable to nest two if statements rather than write a complex boolean expression that is hard to understand, test and debug.