© Irfan Turk 2019
I. TurkPractical MATLABhttps://doi.org/10.1007/978-1-4842-5281-9_5

5. Applications in Simulation

Irfan Turk1 
(1)
Nilufer, Bursa, Turkey
 

In this chapter, we first cover how to generate random numbers. Then, flipping a coin, rolling a pair of dice, random walking, and traffic flow topics are covered. In each section, I provide illustrations of the relevant programming ideas and explain them when necessary.

Random Number Generation

To create sequences of pseudorandom numbers in MATLAB, one of the rand, randn, or randi commands can be used (Table 5-1). We can use the rng function to control the repeatability of the numbers.
Table 5-1

Random Generating Functions

Function

Explanation

Example

rand(n)

rand(n,m)

Creates uniformly distributed pseudorandom numbers between 0 and 1

> rand(2)

ans =

0.8147    0.1270

0.9058    0.9134

randn(n)

randn(n,m)

Creates normally distributed pseudrandom numbers

> randn(2)

ans =

0.3188   -0.4336

-1.3077    0.3426

randi(imax)

randi(imax,x,y)

Creates uniformly distributed pseudorandom integers up to imax

> randi(5,2,3)

ans =

5     5     3

1     5     5

Rng

Controls random number generation

> rng('shuffle')

randperm(n)

randperm(n,k)

Creates row vector containing k unique permutation of integers from 1 to n

> randi(5,2,3)

ans =

2    4    3    1

In a session, we can get different values each time we run one of the rand, randn, or randi functions. If the session is closed and a new session is opened, though, the same values are repeated for the same function used. This happens due to the fact that the rng function uses the same default seed. The default seed is Mersenne Twister with seed 0. If the seed type is changed to shuffle, then we can get different values each time rng is called. However, the randperm(n,k) function creates k random permutation of integers from 1 to n.

Example 5-1. Create seven numbers between 2 and 8 using the rand command .

Solution 5-1. To get seven numbers, we can use a row vector. If we use the rand command, we get numbers between 0 and 1. By multiplying the numbers by 10 and then rounding them, the obtained numbers will be between 0 and 10. If we use mode 7, then all numbers will be between 0 and 6. After shifting the numbers by adding 2, we can get the required numbers. To show all the steps, the following code can be used. However, the complete task can be achieved by typing just a single line as written at the bottom of the code.

Example5p1.m
%Example5p1
%This code produces 7 numbers
MyNumbers = rand(1,7);
MyBigNumb = MyNumbers*10;
MyIntegers = round(MyBigNumb);
MyMod = mod(MyIntegers,7);
MyFinal = MyMod + 2;
disp(['The numbers are: ',int2str(MyFinal)])
%MyFinal=2+mod(round(10*rand(1,7)),7)
Once the code is executed, the following output will be displayed on the screen.
> Example5p1
The numbers are: 3  3  4  7  6  8  2
>

Example 5-2. Using the randperm function , create five integers between 1 and 20. Then, create another sequence of 10 numbers using the randomly selected numbers with the randperm function. The first two elements of the sequence should be the first number created by randperm. The third and fourth elements of the sequence should be the second number created by randperm. The same pattern should be applied to the rest of the elements of the sequence.

Solution 5-2. The following code can be used to accomplish the given task.

Example5p2.m
%Example5p2
%This code uses randperm function
Numbers = randperm(20,5);
Seq= Numbers([1,1,2,2,3,3,4,4,5,5]);
disp('Randomly Selected Numbers:');
disp(Numbers);
disp('Numbers of Sequence:');
disp(Seq);
Once the code is executed, the following output will be shown on the screen.
> Example5p2
Randomly Selected Numbers:
     3     9    19     5     1
Numbers of Sequence:
     3     3     9     9    19    19     5     5     1     1
>

Flipping a Coin

An experiment involving flipping a coin can be performed using the technique in the preceding section, or simply by using the randi(2,1) command as illustrated in Example 5-3.

Example 5-3. Write code that asks the user the number of times to flip the coin. Then the code should call a function to determine the number of tails and heads in a sequence. The code should print the number of tails and heads and the flipped sequence on the screen.

Solution 5-3. The following code can be used to accomplish the given task.

Example5p3.m
%Example5p3
%This code spins coin
Times=input('Number of times to flip the coin? ');
[H,T,Sequence]=FlipCoin(Times)
function [H,T,Sequence]=FlipCoin(Times)
rng('shuffle')
n=1; H=0; T=0;
Sequence = zeros(1,n);
while n <= Times
      Result = randi(2,1);
      if Result == 1
          H=H+1;
          Cond = 'H';
      else
          T=T+1;
          Cond = 'T';
      end
      Sequence(n) = Cond;
      n=n+1;
end
Sequence = char(Sequence);
end

The code calls the FlipCoin function to get random integer numbers with the randi(2,1) command. This command tells MATLAB that one integer will be selected: 1 or 2. Therefore, each time a number is selected. If the number is 1, then this is regarded as heads (H) otherwise, the result is saved as T, which means tails. All of these results are saved to the Sequence variable as numbers corresponding to H and T from the ASCII table. Then once the counting is done, the Sequence variable is converted to H and T using the char function.

Once the code is executed, the following output will be shown on the screen.
> Example5p3
Number of times to flip the coin?
10
H =
     2
T =
     8
Sequence =
    'TTHTTHTTTT'
>

Rolling a Pair of Dice

Programming the rolling of a pair of dice or a single die can be done in several ways. One of the easiest ways is to use the randi(6,1,2) command (or randi(6,1) for a single die). In this way, two integers can be selected between 1 to 6. For an illustration, we can take a look at Example 5-4.

Example 5-4. Write code to simulate rolling a pair of dice using the randi command . The code should ask the user the number of times the pair of dice is rolled. Then all outcomes including the sum of each roll should be displayed on the screen.

Solution 5-4. To get two numbers to represent die, you can use the randi(6,1,2) command. To achieve the task, the following code can be used.

Example5p4.m
%Example5p4
%This code rolls die and prints the sum
N=input('Enter the number of times to roll ');
[Results,Sums] = RollDie(N);
disp('The Rolled Die');
disp(Results);
disp('The Sums For Each Rolling');
disp(Sums);
function [Results,Sums] = RollDie(Number)
Results = zeros(Number,2);
Sums = zeros(Number,1);
for i=1:Number
    Die=randi(6,1,2);
    Sum=Die(1)+Die(2);
    Results(i,1:2)=Die;
    Sums(i)=Sum;
end
end
Once the code is run, the following output is obtained.
> Example5p4
Enter the number of times to roll
5
The Rolled Die
     6     1
     2     6
     5     1
     2     4
     4     5
The Sums For Each Rolling
     7
     8
     6
     6
     9
>

Example 5-5. Write code to simulate rolling a pair of dice. The code should ask the user whether or not the user wants to play. If the user wants to play, the code rolls a pair of dice. If the sum of the numbers is 7, the computer should output “You WON $100” and the obtained numbers and keep rolling. If the sum of the numbers is 10, the computer should output “You WON $50000” and the obtained numbers and keep rolling. For the rest of the sum possibilities, the program should stop running.

Solution 5-5. The following code can be used to accomplish the given task.

Example5p5.m
%Example5p5
%This code simulates a pair of dice
N=input('Enter 1 to roll a pair of dice ');
while (N==1)
    Die=randi(6,1,2);
    switch sum(Die)
        case 7
            disp('You WON $100');
            fprintf('Numbers: %i and %i ',...
                Die(1),Die(2));
        case 10
            disp('You WON $50000');
            fprintf('Numbers: %i and %i ',...
                Die(1),Die(2));
        otherwise
            N=2;
            fprintf('Numbers: %i and %i ',...
                Die(1),Die(2));
    end
end
Once the code is executed, the following output will be printed on the screen.
> Example5p5
Enter 1 to roll a pair of dice
1
You WON $100
Numbers: 2 and 5
Numbers: 2 and 1
>

As shown in the output, after running the program and entering 1, the program began to run. Then, the computer rolled 2 and 5, the sum of which is 7, and printed You WON $100 and continued. On the second attempt, the rolled numbers are 2 and 1, the sum of which is 3. Because 3 is not one of the special cases identified, the code changed the value of variable N, and finished.

Random Walking

A random walk can be simulated by using the rand command as well. This section illustrates one-dimensional and two-dimensional cases separately.

Example 5-6. Write a code to simulate a one-dimensional walk where the directions picked randomly from either 1 or -1 to go either to the right or left for 20 steps.

Solution 5-6. Although the question is one-dimensional, to see the right and left steps clearly, the path will be drawn one step up toward the y direction in each step. The right step will be in red color and blue will indicate the steps to the left. The following code can be used to accomplish the given task.

Example5p6.m
%Example5p6
%The code simulates random walk in 1-d
close all; Y=1; P = 0;%position
Steps = 20; Step = 1;
for i=1:Steps
    W = rand;
    if W>0.5
        P = P + Step;
        St = linspace(P-1,P,21);
        plot(St,Y,'r*')
        hold on
    else
        St = linspace(P,P-1,21);
        P = P - Step;
        plot(St,Y,'b+')
        hold on
    end
    Y = Y + 1;
    pause(0.5)
end
grid on
xlabel('Red-->right | Blue-->left')
ylabel('Direction in each step')
title('Random Walk in Each Step')
disp(['Final Place :',num2str(P)])
Once the code is run, the output shown in Figure 5-1 is obtained.
../images/483991_1_En_5_Chapter/483991_1_En_5_Fig1_HTML.jpg
Figure 5-1

Output of Example5p6

The random walk starts by going left at the beginning. Then it goes right, then left again, and so on. At the end, the position is six steps left from the starting point. At the prompt, we also obtain the following result.
> Example5p6
Final Place :-6
>

Example 5-7. Write code to simulate a two-dimensional random walk. In each step, the computer can go just one step right in the x direction, or one step up in the y direction in 15 steps.

Solution 5-7. The following code can be used to accomplish the given tasks.

Example5p7.m
%Example5p7
%The code simulates random walk in 2-d
close all;clear all;P = 0;%position
Steps = 15;X=0;Y=0;Step = 1;
plot(X,Y,'co');hold on
format short
for i=1:Steps
    W = rand;
    if W<0.5
        St = linspace(X,X+1,21);
        X = X + Step;
        plot(St,Y,'r*')
        hold on
    else
        St = linspace(Y,Y+1,21);
        Y = Y + Step;
        plot(X,St,'bs')
        hold on
    end
    pause(0.5)
    disp([X,Y])
end
grid on
xlabel('Red-->Right | Blue-->Up')
ylabel('Direction in each step')
title('Random Walk in Each Step')
Once we run the code, the graphic shown in Figure 5-2 is obtained.
../images/483991_1_En_5_Chapter/483991_1_En_5_Fig2_HTML.jpg
Figure 5-2

Output of Example5p7

As Figure 5-2 shows, the walk went right seven times and upward eight times. That total gives us the total number of steps in the code.

At the prompt, we also got the following after running the code.
> Example5p7
     1     0
     2     0
     2     1
     2     2
     2     3
     2     4
     3     4
     4     4
     4     5
     5     5
     5     6
     5     7
     5     8
     6     8
     7     8
>

Traffic Flow

In this section, we use an image function, imagesc , to represent vehicle traffic with color. In other words, we color different sections of the road to represent traffic flow.

Example 5-8. Write code to show a flow for a vehicle where the width and length of the road are 5 and 20 units, respectively.

Solution 5-8. The following code can be used to accomplish the given tasks.

Example5p8.m
%Example5p8
%This code shows traffic flow
rw=5;%road width
rl=25;%road length
road = zeros(rw,rl);
xpos=2;ypos=4;
road(ypos,xpos)=1;
imagesc(road)
axis equal
for t=0:20
    %clear previous vehicle
    road(ypos,xpos)=0;
    %update new position
    xpos=xpos +1;
    road(ypos,xpos)=1;
    %plot new position
    imagesc(road)
    Time=sprintf('Time: %i',t);
    title(Time)
    axis equal;
    pause(0.4);
end

As shown in the code, after moving to the right side in each iteration, the color of the vehicle road is assigned to 0. To move forward, the color of the road is assigned to 1. And each time, the colors are displayed with the imagesc function. This is done to display a traffic flow in a graphic form. Between each frame, the computer waits 0.4 seconds to see the simulation slowly.

Figure 5-3 shows the final frame of the simulation done with the code.
../images/483991_1_En_5_Chapter/483991_1_En_5_Fig3_HTML.jpg
Figure 5-3

Output of Example5p8

Example 5-9. Write code to show a flow with two separate directions of traffic: going and coming. On each road, there should be one vehicle driving.

Solution 5-9. The following code can be used to accomplish the given task.

Example5p9.m
%Example5p9
%This code shows traffic flow
rw=11;rl=25;
road = zeros(rw,rl);
road(6,:)=1;
x1pos=2;y1pos=9;
x2pos=19;y2pos=3;
road(y1pos,x1pos)=1;
road(y2pos,x2pos)=1;
imagesc(road);axis equal
for t=0:15
    %clear previous vehicle
    road(y1pos,x1pos)=0;
    road(y2pos,x2pos)=0;
    %update new position
    x1pos=x1pos +1;
    x2pos=x2pos -1;
    road(y1pos,x1pos)=1;
    road(y2pos,x2pos)=1;
    %plot new position
    imagesc(road)
    Time=sprintf('Time: %i',t);
    title(Time);axis equal;
    pause(0.4);
end
Once the code is executed, the output shown in Figure 5-4 is displayed on the screen.
../images/483991_1_En_5_Chapter/483991_1_En_5_Fig4_HTML.jpg
Figure 5-4

Output of Example5p9

Problems

  • 5.1. Create 10 numbers between 3 and 7 using the randi command.

  • 5.2. Using the randperm function, create seven integers between 1 and 15. Then, create another sequence of 20 numbers using randomly selected numbers with the randperm function. The first three elements of the sequence should be the first number created by randperm. The fourth, fifth, and sixth elements of the sequence should be the second number created by randperm. The same pattern should be applied to the rest of the elements of the sequence.

  • 5.3. Write code that flips a coin 20 times. The code should print the number of tails and heads obtained and the flipped sequence on the screen.

  • 5.4. Write code to simulate a pair of dice rolled 10 times using the rand command. All outcomes, including the sum of each roll, should be displayed on the screen.

  • 5.5. Write code to simulate a pair of dice. If the sum of the numbers is 5, the program should write “You GOT $200” and keep rolling. If the sum of the numbers is 12, the program should write “You GOT THE BIG PRIZE!!” and keep rolling. If the sum of the numbers is 8, the program should stop; otherwise it should keep running.

  • 5.6. Write code to simulate two-dimensional random walking. In each step, the computer can go just one step left in the x direction, or one step down in y direction for 20 steps.

  • 5.7. Write code to show a flow for two vehicles where the width and length of the road are 6 and 24 units, respectively.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.199.27