Crash Course in MATLAB® for Probability

Nancy K. Stanton

based in part on original versions of "Introduction to Matlab®" © 2000-2005 by Paul Green and Jonathan Rosenberg

Contents

Starting MATLAB

Launch MATLAB. You should see the MATLAB Desktop which includes several windows, the most important of which is the MATLAB Command Window. (The function of the other windows is explained in Chapter 3 of A Guide to MATLAB® for Beginners and Experienced Users, second edition, by Hunt, Lipsman and Rosenberg, which is on the reference shelf in the Mathematics Library.)

In the toolbar, change the Current Directory to the directory or folder where you want to save your work.

In the command window you should see a prompt that looks like >>. Position your mouse there and type

1+1

and hit Enter. MATLAB should type in response:

ans =
    2

In this way you can use MATLAB as a calculator. Now type sin(pi) and hit Enter. MATLAB should type in response something like:

ans =
     1.2246e-016

MATLAB recognizes sin as the sine function and pi as the number $\pi$. Of course $\sin(\pi)=0$, but MATLAB gave the numerical answer $1.2246 \times 10^{\mbox{-16}}$ (in scientific notation). This is because MATLAB does arithmetic with double-precision numbers, which are only accurate to 15 places. The MATLAB default is to print five digits, but you can change this by typing format long and hitting Enter. Thereafter, MATLAB will print out 15 significant digits (unless you go back to the default by typing format short).

Exercise

Experiment with using the MATLAB Command Window as a calculator. The basic operations and functions are represented by * for "times", / for "divided by", ^ for powers (e.g., 3^3 means "3 cubed"), abs for absolute value, sqrt for square root, exp for the exponential function to the base e, so exp(1)=2.718281828..., log for the logarithm function to the base e (often denoted ln), sin, cos, and tan for the basic trig functions, cosh, sinh, tanh for the basic hyperbolic functions, and asin, acos, atan for the inverse trig functions.

Numerical vs. Symbolic Calculation

It is important to remember that MATLAB, by default, does numerical calculations with double-precision numbers. It can also do exact, i.e., symbolic, calculations and algebra, using an accessory called the Symbolic Toolbox, but only if you tell it to. For example, notice what happens if you type sin(sym('pi')) and hit Enter. You should see:

sin(sym('pi'))
 
ans =
 
                                       0

A string of characters, enclosed in single quotes, is what MATLAB calls a string. The command sym takes a string as an argument and tells MATLAB to interpret this string as a symbolic expression. So sym('pi') refers not to the approximate number 3.14159265... (which MATLAB denotes simply by pi) but to the exact number $\pi$. So now when we take the sine, we get the exact answer 0. If you look carefully, you'll see that MATLAB indents its answer a few spaces when the answer is numerical (double-precision) and indents it a lot when the answer is symbolic. That way you can always distinguish numerical from symbolic output.

The usual way to do symbolic calculations in MATLAB (to avoid having to keep writing such awkward expressions as sym('x') over and over) is to declare certain variables to be symbolic. Such a declaration lasts until you clear the assignment or assign a numerical value to that variable instead. Here's an example. Type syms pi and hit Enter. That's equivalent to saying, "From now on I want pi to represent the true $\pi$, not the approximation." The command syms declares whatever follows to be a symbolic variable or expression. Note the lack of indentation. If you now type sin(pi) and hit Enter as before, you should see the same result.

If you now type clear pi and hit Enter, then hit the "uparrow" key twice (a shorthand for recalling the next-to-last command) to recover sin(pi) and hit Enter, you get

ans =
   1.2246e-16

again.

Getting Help in MATLAB

To use MATLAB effectively it's important to know how to look up the syntax for hundreds of commands that you can't possibly memorize. There are many ways to get online help. If you remember the name of a command, but can't remember its syntax or all its options, all you have to do is type help followed by the name of the command. For example, try:

help rand

For the most complete MATLAB help, you will want to use the Help Browser. To access help on a specific command in the Help Browser, you can type (in the Command Window) doc followed by the name of the command. For instance, compare the result of doc rand with that of help rand. You can also search for the item using the search box next to the ? on the HOME page of the MATLAB desktop or in the search box in the Help Browser, which you can launch by clicking on the ? above Help on the HOME page. Also, typing (in the Command Window) lookfor followed by a keyword will get you a list of all the MATLAB commands with that keyword in their basic description.

The MATLAB Workspace

As you work in MATLAB, you will usually end up defining various variables and objects. These are saved in the MATLAB Workspace. There are two ways to inspect the contents of the Workspace: with the Workspace browser, usually found on the right side of the Desktop, or with the whos command. This lists all the currently defined variables and their "types" (double (i.e., double-precision numeric), string, symbolic, etc.). Most of the time you will see a variable called ans; MATLAB uses this for the last output that you did not explicitly store somewhere else, so the contents of ans will usually change many times during a session. Variables can be removed from the Workspace (for instance, to save memory space) with the clear command. Consider the following example.

a='pi'; b=sym('pi'); c=pi; whos
  Name                 Size            Bytes  Class     Attributes

  A                    1x1                 8  double              
  a                    1x2                 4  char                
  ans                  1x1               232  sym                 
  b                    1x1               232  sym                 
  c                    1x1                 8  double              
  toolbox_version      1x5                10  char                

Here a is of type "char" (a string), b is of type "sym" (symbolic), and c is of type "double". Allowable variable names must be strings of letters, underscores, and numbers starting with a letter, but both upper-case and lower-case letters are allowed, and MATLAB distinguishes between them. Don't be fooled by the fact that the help lines for a command often refer to the command in all caps; MATLAB's built-in commands are almost all to be typed entirely in lower-case letters.

MATLAB editor

The MATLAB editor allows you to store a number of MATLAB commands in a script m-file. The file should be divided into units called sections or cells, each beginning with a double percent sign.

Create an m-file. On the desktop HOME page, click on New Script at the left of the menu bar. The MATLAB editor will open a new window. In the EDITOR menu bar, click on Save then Save As then give your file a name. The name can include an underscore but not a hyphen and it can't start with a number. Be sure it ends in .m so MATLAB that it's an m-file. Save your work often.

Now click on the PUBLISH tab above the EDITOR menu bar, then on Section with Title and replace SECTION TITLE by the title you want to give to the document you're about to create. Replace DESCRIPTIVE TEXT by a more elaborate description or delete that line. (You can also just type %% then leave a space and type your title. Now press Enter. You can type % at the start of the next line then leave one space and add your more elaborate description.) Now click Enter. You should have a blank line, where you can enter a MATLAB command. Now evaluate the section by clicking on the EDITOR tab then on Run Section in the tool bar. MATLAB will execute the commands in the cell and display the result in the Command Window. For example, try typing rand. This gives you a random number between 0 and 1.

Create a new section by clicking on Section (or typing %%)

Now try typing rand(1,5). This should give you a row of 5 random numbers.

Remember to save often and to use lots of sections (cells).

Toss a coin 10 times

Suppose you want to write MATLAB code to toss a fair coin 10 times, print out the resulting string of heads and tails, and tell you how many heads there were and what proportion were heads. Type the following lines, then run the section.

A=0;
heads = 0;
for i=1:10
    if rand <= 1/2
        A=[A,'H'];
        heads = heads+1;
    else A = [A,'T'];
    end
end
A
heads
proportion = heads/10

How does the code work? First you initialize the values of A and heads. A will store the results of the tosses. Then you have a for loop, which does something for each value of i from 1 to 10. We simulate the coin toss by using rand and consider the result to be a head if the random number is less than or equal to 1/2, and otherwise a tail. So we test to see if it is less than or equal to 1/2. If so, the code has MATLAB put the string 'H' in A and increase heads by 1; otherwise it puts 'T' in A. At the end, MATLAB prints A, heads (the number of heads) and the proportion of heads.

You can add a comment to your code by adding % at the end of a line of code, then following that with your comment. For example you could make the first line

A = 0; % initialize A

The semi-colon at the end of a line of code causes MATLAB to suppress the output. Here you probably only want to see the final ouptut, not the output after each toss, which is why there are semicolons. Modify your code by deleting the semicolons to see what happens when they aren't therere.

Publishing

The web page you are reading was produced using MATLAB's editor and publish feature. When you publish the file, MATLAB displays all the commands, output, and graphics in a web page - assuming there are no MATLAB errors. All of the output of a sectiion appears immediately after all of the input of the section. This means you want to have lots of sections, so you can tell what output goes with what input.

WARNING: If there is an error message, the web page will show that, and MATLAB will show the rest of your input but will NOT execute any of the remaining commands.

You can display formatted text that as far as MATLAB is concerned consists only of comments (not for evaluation). Click on Preformatted Text towards the right on the menu bar of the publish tab. Make sure each line of what you want formatted starts with % followed by a space and that you don't leave any completely blank lines. When your file is complete and you are sure there are no errors, you can publish it by clicking on the arrow above Publish on the toolbar.

After publishing, you can either display the web page in your web browser or print it out (in order, say, to turn in a homework assignment). You might find that the printed version looks better if you open the .html file in Chrome, Firefox or Internet Explorer and print from there instead of printing from MATLAB's browser. You can also choose to publish to pdf instead of html.

First MATLAB problem, Section 1.1 #3

This problem requires you to simulate rolling 3 dice and summing the result. Download the file dice_sum.m and put it in your MATLAB path.

Give the command doc dice_sum to see what it does.

Give the command type dice_sum to see the code. Try to understand how it works.

Try it with 3 dice and a small number of rolls, say 10 or 20, to see how it works.

Now open an new script m-file and save it with an appropriate name. Use Section with Title to give it a title and put your name on the next line. You might want to create a new section for each part. For (a), if you're using dice_sum from the website, say that's what you're doing. If you use something else, say what, and if it's your own code or you modify the code on the website, include the code by typing

type my_dice_sum

where you replaced my_dice_sum by the name of your command. Now use it with a large number of rolls to find the proportion of 9s and the proportion of 10s.

Now create a new section for (b). You can type your answer there, using Preformatted Text. Just be sure that every line starts with % followed by a space.

Save your file and publish it.