CS310 Team Lab #6
Sequential and Iterative Execution
Programming

OBJECTIVES

INTRODUCTION

In this team lab you will write code to implement algorithms that are described in pseudocode. The algorithms each team writes will help you gain experience both with writing MATLAB programs and in the use of the randperm() and the input() functions. The algorithms you write will involve repeating steps multiple times (i.e., iteration) and you will get experience using for loops to implement iteration in MATLAB.

PROBLEMS

Problem 1: Generating random values

For any positive integer n the MATLAB function randperm(n) generates a random permutation (ordering) of the positive integers from 1 to n.

  1. In the Command Window try the randperm(n) function for a few values of n, including n=2 and n=6 and consider the results.

  2. Now, create a new script (m-file). Add the clear command to the top of your script. How could you use the randperm function and arithmetic operation(s) on the result to get a random listing of other sets of values? Add code to your script to create a random listing these values:

    [0.1, 0.2, 0.3, ... 0.9]

  3. Next, add code at the beginning your script (below the clear command) to define a variable n. Then, add code to your script to create a random ordering of the values from -n to n:

    [-n, ..., -3, -2, -1, 0, 1, 2 3, ..., n]

    Test your script by setting n to different values and running it, making sure that your code creates the vectors containing all the expected values (albeit in random order). Try n = 2, 5, 10, 15.

  4. Below is one way we can represent at deck of playing cards in MATLAB. Copy and paste the definition of DECK into your script.

    DECK = ['AH';'2H';'3H';'4H';'5H';'6H';'7H';'8H';'9H';'TH';'JH';'QH';'KH'; ...
    'AS';'2S';'3S';'4S';'5S';'6S';'7S';'8S';'9S';'TS';'JS';'QS';'KS'; ... 'AD';'2D';'3D';'4D';'5D';'6D';'7D';'8D';'9D';'TD';'JD';'QD';'KD'; ...
    'AC';'2C';'3C';'4C';'5C';'6C';'7C';'8C';'9C';'TC';'JC';'QC';'KC']

    Note: DECK is a 52×2 matrix of single characters, where each row contains two characters: column 1 represents the rank (value) and column 2 represents the suit of the card.

    Write a for loop to display the deck of cards in order, one card per row. (Note: technically, we don't need a for loop to do this in MATLAB, however, one important goal of this lab is to give you experience writing for loops - so use a for loop here.)

  5. We wish to display the deck of cards in random order (in other words, shuffle the deck). Here is an algorithm (written in pseudocode) that can do this:

    Create the DECK of cards (as shown above)
    Get a random permutation of the correct length
    for each value in the random permutation
        display the corresponding card (row) of DECK

    Add code to your script that implements the algorithm above. As with the previous part, make sure to use a for loop.

Show your script for problem 1 to a lab leader and demonstrate that it works correctly.

Problem 2: Simple simulations

We wish to simulate the problem of a bug hopping on a grid of equally spaced points. At any position on the bar, the bug has equal probability of going to the position to the right or to the left. The algorithm for this type of simulation is very straightforward.

  1. First, save these two function definitions to your current directory and review the comments for each function to learn what they do and what parameters they require.

    moveBug.m : moves a bug one hop to the left or one hop to the right

    drawBugOnBar.m : draws a bar with N positions and a bug at position P on a plot figure. It also displays the current number of hops taken and allows the caller to change the wait time (so it doesn't run too fast).

  2. In the Command Window, call the moveBug function several times, making sure you understand what information is passed to moveBug and what moveBug returns. Then, call the drawBugOnBar function several times, making sure you understand what information is passed to drawBugOnBar and what drawBugOnBar returns.

  3. Open a new script (m-file) and, in the script, write an algorithm using pseudocode that uses the two functions given to simulate a bug hopping H times on a bar with N positions.

    Now, select the text for all of your algorithm. In the menu bar of the Editor tab you should see a Comment option with three icons to the right of it. Click on the icon that is just a percent sign (%). You've just created the comments for the code you will be writing in part d! After each step in your algorithm, you should add the code that implements that step.

  4. Add code to your script to implement the algorithm you developed. Run your simulation for 10 hops on a bar with 9 positions. Start the bug at position 5 (middle of bar).

  5. Simulate a bug hopping 5 times on a bar with 5 positions and bug starting at position 3.

  6. Simulate a bug hopping 25 times on a bar with 21 positions and bug starting at position 11.

  7. Simulate a bug hopping 100 times on a bar with 25 positions and bug starting at position 13.

  8. How many lines of code did you have to change to run each new simulation?
    Your answer should be: "We only had to edit the three constants we defined at the start our program."

    What happens when the bug falls "off" the bar?

    How would you change the odds in problem 2 so that the bug has a 75% chance of hopping left and a 25% chance of hopping right?
    Hint: only the moveBug function must change.

Problem 3: Simulations based on user input (values entered via keyboard while program is running)

Modify your script from problem 2 so that it prompts the user for and accepts the number of hops and the number of positions as input from the user and then runs the simulation as described in problem 2.

  1. First, ask the user for the number of positions on the bar and the number of hops to simulate.
  2. After getting the number of positions on the bar, initialize the starting position of the bug to be in the middle of the bar. Be sure that the position is a whole number. (Hint: use a mathematical function.)
  3. Run your program a few times to see that it works as expected.

What happens if the user enters a negative number for the number of hops or for the number of positions on the bar?

Next week, we will learn how to check user input values before using them in the code that follows. For today, just observe the problems that can arise when users do not input values as requested, expected, and required.

Have a lab leader confirm that your program works for valid input values.

ADDITIONAL PROBLEMS or FURTHER READING

Additional Problem 1: Bug on a plate

Extend your bug hopping on a bar to a bug hopping on a 2-d plate:

  1. First, using drawBugOnLine as a guide, write a drawBugOnPlate function. For simplicity, assume the plate is square and the input parameter N is the length of one side of the plate. Draw the plate so its lower-left corner is at the origin and instead of passing in a single value P as the position, have your drawBugOnPlate function assume that P contains the (x, y) position of the bug, i.e., P is a vector containing two values, representing the x- and y-coordinates, respectively.

  2. Then using moveBug as a guide, write a moveBugOnPlate function that takes the position of the bug (again as a point) and randomly moves the bug north, south, east, or west to a new position (which is the position that is returned).

  3. Finally, modify your script from Problem 3 so that the user now enters the initial position of the bug as a point (i.e., a vector with 2 values) and the code simulates the bug hopping on the 2-d plate.

Additional Problem 2: Is a point inside or outside of a triangle?

The ability to determine where points are with respect to shapes and surfaces is an important one in computer graphics as well as computer-aided design. Being able to determine if a point is inside a triangle is a precursor to determining if points are inside polygons.

The function insideTri() determines whether a given point is inside or outside of a triangle. By reviewing the comments and code you can see it that solves a linear system to determine if a point is inside a triangle. If you are interested, a more detailed explanation of the linear system that solves this problem is given in this appendix. For this lab, save a copy of this function to your current directory: 

insideTri.m : determines if a point is inside a triangle or not

DO NOT EDIT THE insideTri FUNCTION. Type help insideTri and read the information that describes how you use the function.

  1. Call the insideTri() function from the Command Window to determine if the point (1.5,0.75) is inside the triangle formed by these three points: (0,0), (2,0), and (1,2).

    >> result = insideTri( [ 1.5,0.75] , [0, 2, 1], [0, 0, 2] )

    What does the result mean? Is the point inside the triangle or not?

  2. Complete the test_insideTri script.

    It is often useful to write functions or program scripts whose sole purpose is to test the correctness of another function. We have provided a header, some comments, and a function that plots triangles and a single point, to help you get started. Save these two m-files in your current directory.

    In the test_insideTri script, create a separate cell for each of these test cases (so that you can see each plot figure) to the script named test_insideTri.m Each cell should plot and display the results of calling insideTri for its point and triangle combination. The first case has been done for you.

  3. Publish your test_insideTri script to see the test's plot and result.

    What do the results mean? Based on these three cases, does insideTri work or not?

There are two additional problems to consider. To make this team lab write-up a little shorter, they are on described on a separate page: