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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.