CS 221 Lab 5 Fall 2011: Functions, Arrays, and While Loops in MATLAB

Out: 5 October 2011
Due: 13 October 2011

Note Well: The purpose of lab exercises is for you to learn how the tools work. The purpose is not for you to type something into MATLAB or Excel. As you go through the steps of each exercise, think about what you are doing and what the program is doing, and try to predict what you will see. If you don't understand something, ask your instructor -- that's what he's there for.


Part 1: User-defined Functions in MATLAB

In lecture we saw how to define new functions in MATLAB. In this exercise you will create a simple function and invoke it.

  1. Go through the Tutorial "Using MATLAB Function Files" in section 3.4 of your text; stop at the bottom of page 85. Note: although an end command at the end of the function is not technically required (and is omitted in the text example), it is a good idea to always include it.

  2. Now you will create a new function by modifying your area_rect function. The new function will take three arguments, corresponding to the base, height, and depth of a rectangular prism; it will return the volume of the prism. (Of course, the volume is simply the product of the base, height and depth.)

    1. Copy the file area_rect.m to a new file vol_prism.m.
    2. Double-click on vol_prism.m in the MATLAB Current Directory window, to open it in the editor. Modify the file as needed to create the new function vol_prism: change the comment so it accurately reflects what the function is doing, change the function name, add the third input variable (argument), and change the expression for computing the result. You probably also want to change the name of the output variable.

      Note this general principle: variables should have names that describe what they store. It is a bad idea to have a variable that stores volume be called "area".

    3. Save the modified function in the "Current Directory".

  3. Now test the vol_prism function by invoking it with several sets of arguments (e.g. vol_prism(3,4,5)). Demonstrate for your instructor that it always returns the correct answer.

  4. Upload the modified function via the CS Portal as as "Lab 5 Part 1". page.


Part 2: Working With Arrays in MATLAB

In this exercise you will experiment with creating and modifying arrays in MATLAB. You will also learn how to use the "diary" command to record an interactive session with MATLAB.

  1. Clear the command window and the workspace. Bring up the Help window (select "Product Help" under the "Help" menu). Search for "diary". Read the entry for the "diary" command.

  2. Type "diary" at the command prompt. From now on, MATLAB is recording everything you type and everything it prints out (excluding graphics and color, etc.). You will see a file called "diary" in the "Current Directory" window.

  3. Read, do, and understand all of the steps of the Tutorial "Computing With One-Dimensional Arrays" on pp. 86-91 in the textbook (first part of Section 3.5). Note: stop before example 3.7).

  4. Read, do, and understand all of the steps of the Tutorial "Computing with Two-Dimensional Arrays" on pp. 93-96 of the textbook (first part of Section 3.6). Note: stop before example 3.8.

  5. Now clear the workspace. Create a 2x4 array called "test" with the following contents:
    99.9 1.01 0 782
    105.789 200.381 33 -1

  6. Now change the entry that is equal to zero so it is -55 instead.

  7. Sometimes you might have to stop in the middle of working with MATLAB. Rather than lose all your work (i.e., the values of variables you have created and computed with), you can use the save command to make MATLAB store variables' values in a file. Read the Help for the save command. (Note: be sure to do this in a separate window, and do not type "help save" in the command window.) Use the save command to store the contents of the array named test in a file named "Lab5test.txt", in "ascii" (i.e. text) format:
    >> save Lab5test.txt test '-ascii'
    
    (Note: the single quotes should be included.) You should see a file "Lab5test.txt" in the "Current Directory" window. Double-click on it and verify that it contains the values of that were in array test. (Note: if you don't give the string "-ascii" as the third argument, MATLAB saves the file in a different format, which is more compact, but not as easily readable.)

  8. Now clear the array test from your workspace. When you have done so, use the "load" command to read back in the contents of the file you just created:

    >> load Lab5test.txt '-ascii'

    Notice that the variable Lab5test is created, and has the same contents as the former array test.

  9. Type "diary off" at the command prompt. This stops MATLAB recording your session. Look in the "Current Directory" window. There should be a file called "diary". Double-click on it; MATLAB brings up an editor window. You should see everything you typed during the session, along with what MATLAB printed in response. (The command prompt will not show up in the file.)

  10. Now upload your diary file via the CS Portal as as "Lab 5 Part 2".


Part 3: Iteration with while

As mentioned in lecture, the power of computers lies in their ability to do things over and over, i.e., to iterate a step or series of steps. The while construct tells MATLAB to iterate a step (or sequence of steps) as long as a given condition (i.e., a boolean expression) remains true. Its syntax is very similar to that of the basic if statement, with which you are already familiar:

      while  <boolean expression>
         <statements>
      end

One of the times we want to be able to iterate is when getting input from the user. We've used if statements in past scripts to test for valid input values. However, when the user makes a mistake, the only thing we can do is complain and exit. We'd like to give the user another chance. In this exercise you will modify an existing script to make use of a while loop when reading input from the user.

  1. Download the script file roots.m and save it to your desktop.

  2. Type "roots" at the command prompt to run the script. Input a negative value. Now run the script again so you can input a valid (non-negative) value.

  3. Now bring up roots.m in the script editor. (Double-click on the filename in the "Current Directory" window.) Look over the script in the editor.

  4. We are going to replace the if-else statement with a while statement.

    1. Replace the if in the script with while.
    2. Replace else with end.
    3. Now there are two ends; delete the second one (the whole line).
    4. Un-indent the three disp statements so they line up all the way to the left.

  5. Now, if you run the script and enter a negative number, it will print "Sorry, the number must be positive" over and over until you type CTRL-C. (Find the CTRL key and then try it.)

  6. The problem here is that the body of the while-loop does not modify x, so the boolean expression can never become false once it is true!

    To fix this, copy the line that calls input() to get the value of x after the line that prints the error message. That is, after telling the user they made a mistake, prompt again for the value.

    Demonstrate the modified script to your instructor, and then upload it via the CS Portal as as "Lab 5 Part 3".


Summary: Things You Learned