HINTS for using MATLAB - Math 408 - Spring 2009

  • Click here for Math408 home page
  • Click here for Prof. Sawyer's home page
    Top of this page

    Table of Contents:
       1. WARNING: Serious potential bug within MATLAB programs
       2. Special Math408 MATLAB functions
       3. Printing and copying program output
       4. Keeping a diary (writing a text file from selected command-window output):
       5. Formatting tables using fprintf()
       6. Within-program functions and subroutines
       7. Using MATLAB from a command-prompt window

    
    

    1. WARNING: Serious potential bug within MATLAB programs
       If you enter

    x = 1 + 2 + 3
        + 4 + 5;

    within a MATLAB program, you will get x=6 and not the correct value for 1+2+3+4+5, which is x=15. The second line will be completely ignored, without even an error message.

       You can get an idea of how MATLAB is thinking if you enter the same two lines in the MATLAB command window. Your entry and MATLAB's response will be

    >> x = 1 + 2 + 3

    x =

        6

    >>     + 4 + 5;

    (No response from MATLAB)

       What has happened is that MATLAB interprets ``x = 1 + 2 +3'' as a complete command, and returns x=6. In the next line ``+4+5;'', MATLAB thinks that you just want to add 4 and 5 together, with the trailing semicolon (;) meaning that you are not interested in the answer.

       While this behavior causes no problems at the command line, within a MATLAB program it can cause incorrect results with absolutely no indication of any problems.

    
    

    2. Special Math408 MATLAB Functions:
       The files

         normpval.m   normint.m   pvchisq.m   pvtdist.m   pvfdist.m   binomtail.m   getmidranks.m

    on the Math408 Web site provide functions of the same names that can be used in MatLab programs. For example, pval=normpval(z) returns the two-sided P-value based on the standard normal distribution for a statistic with Z=z. The function p=normint(z) returns Prob(Z le z) where Z is standard normal.

       Similarly, pvtdist.m can be used to find two-sided P-values based on the Student-t distribution. Specifically, pval=pvtdist(tt,19) returns the two-sided P-value for T=tt, where T (given H_0) has a Student's t-distribution with 19 degrees of freedom. See the comments in the first few lines of each of these function files for the syntax of using the function. Functions similar to the first five functions listed above are in the MATLAB Statistics Toolbox, but your particular copy of MATLAB may not have this toolbox installed.

       To use one of the functions listed above in a program, copy the MATLAB function file (such as pvtdist.m or normpval.m) into the default directory (or Current Directory) of your MATLAB program. The corresponding function (pvtdist() or normpval()) will then be immediately available to you. The name of the Current Directory is shown in an edit-and-browse window at the top center or top right of the MATLAB screen. (Function files can also be copied into any directory on the ``MATLAB path'', if you wanted to keep MATLAB function files in another directory.)

       You can also find the name of the Current Directory by entering

        >> pwd

    in the MATLAB command window. (>> stands for the MATLAB cursor.) Here pwd stands for ``print working directory''. (The name is borrowed from UNIX.) The contents of the Current Directory will sometimes be displayed on the left-hand side of the MATLAB screen. Alternatively, you can display the contents of the Current Directory by entering

         >> dir     OR     Desktop | Current Directory

    Here ``dir'' is entered in the MATLAB Command Window, and | stands for ``and then click on''. That is, click on that option in the Desktop drop-down menu. The MATLAB command

         >> what

    lists the available MATLAB program and function files in the current directory.

       In general, MATLAB program files are of one of two types: MATLAB programs like Firstm.m and WcxSignRank.m on the Ma408 Web site, and MATLAB function files like normpval.m etc. MATLAB function files have a slightly different syntax than MATLAB program files. The names of function files on the Math408 Web site begin with a lower-case letter and those of example MATLAB programs begin with an upper-case letter.

    
    
    3. Printing and Copying Program Output:
       You can print the contents of the MATLAB Command Window by clicking on

         File | Print...

    where | stands for ``and then click on''. That is, click on that option in the drop-down File menu.

       The difficulty here is that this prints THE ENTIRE Command Window output, perhaps including the output of several previous versions of your program that did not work. To CLEAR the Command Window, enter

         >> clc     OR     Edit | Clear Command Window

    where, again, >> stands for the cursor in the MATLAB Command Window. You can now enter the name of your program file (such as >> myfile for myfile.m) and get clean output.

       Another difficulty is that the above operations do not clear MATLAB's internal variable stack. That is, if you calculate a variable named Zvalue (for example), then accidentally delete the code from your program that calculated Zvalue, then the previous value of Zvalue will be used and/or displayed whenever you run myfile. You may only notice that something is wrong if you run myfile again the next day after exiting MATLAB and then get an Undefined Variable error message. To clear MATLAB's interval variables, enter

         >> clear     OR     Edit | Clear Workspace

    As you might expect, not clearing the variable stack before running a MATLAB program can cause incorrect program output due to typos or due to unnoticed references to variables that you no longer want. These types of errors are very hard to detect in the output, but can be eliminated by periodically clearing the variables as above.

    
    
    4. Keeping a diary (writing a text file from selected command-window output):
       You can write the Command Window to a text file, or part of the Command Window to a text file, by first entering

         >> diary mylog.txt

    Thereafter, anything that is displayed in the Command Window will also be written to mylog.txt. To stop writing (and close the file so that you can print it), enter

         >> diary off

    Entering >> diary mylog.txt again (or >> diary on) continues to append text to mylog.txt. To start over, enter

         >> delete mylog.txt

    This deletes the text file, so that you can start afresh.

    
    
    5. Formatting tables using fprintf()
       If you enter
          xx = [ 1   23  3;
                 2  720  4;
                 3   11  1;
                 4   12  2 ];   
    then you can display the matrix xx more-or-less exactly as it is displayed above by entering xx or disp(xx), either in the MATLAB Command Window or in a MATLAB program. However, if
          xx = [ 1   23  3;
                 2  720  4;
                 3   11  1.5;
                 4   11  1.5 ];   
    then entering xx or disp(xx) will display
        1.0000   23.0000    3.0000
        2.0000  720.0000    4.0000
        3.0000   11.0000    1.5000
        4.0000   11.0000    1.5000	
    The first column is now confusing as row or observation numbers, and the final column is confusing as midranks.

       However, MATLAB has borrowed (and slightly improved) a function from C/Java for better displays of matrices or tables. If you enter in a program (or in the MATLAB command window):

       fprintf('  %d   %3d   %4.1f\n', 3, 11, 1.5)  
    then you will get as output
     
        3 11 1.5
    as opposed to
     
        3.0000 11.0000 1.500
    which is what you would get from entering [3 11 1.5].

       In the `format string' ' %d %3d %4.1f\n' in the fprintf() command,

        %d     stands for `display as integer'
        %3d    stands for `display as integer, using AT LEAST 3 spaces, right justified'
        %4.1f  stands for `display as number with possible fractional part,
                 using AT LEAST 4 spaces, with 1 SPACE beyond the decimal point'
        \n     stands for end-of-line (or new line), which you must say explicitly
     
    Arguments following the format string in fprintf() are matched one-by-one with the format instuctions in the format string.

       If fprintf() has a matrix argument after the format string, each COLUMN of the matrix is matched to the format items in the format string. In this case, you will usually want to use the TRANSPOSE of a matrix as the argument in the data. For example, for the 4x3 matrix xx defined above

       fprintf('  %d   %3d   %4.1f\n', xx')  
    displays
          1   23    3
          2  720    4
          3   11    1.5
          4   11    1.5	
    Note that `%3d' has causes the second column to align correctly, and `%4.1f' does similarly for the third column. In this example, using `%4.1f' instead of `%3.1f' has introduced an extra space between the second and third columns, but also provides protection in case you later enter a row with data `7 311 11.5'. That is, the 3rd column will still line up at the decimal points.

       A FINAL COMMENT: In MATLAB, you MUST ENCLOSE the format string with single quotes (' ') and NOT double quotes (" "). The latter will give a format error. In contrast, in C or JAVA, you MUST USE double quotes to enclose the format string, and single quotes will give a format error. This difference takes a bit of getting used to if you are more used to C or MATLAB and switch to the other.

    
    
    6. Within-program functions and subroutines
       The usual way to include a subroutine or a special function in a MATLAB program is to write a MATLAB function file. This is convenient to do, but if you have a directory with several MATLAB program files, each with several MATLAB function files, it may be difficult to see what belongs to whom.

       MATLAB also has a feature for defining and using a subroutine or function within the same MATLAB program file. For example, if you say

    ff = inline('x^2 + y^2')

    near the top of your MATLAB program file, then f(x,y) will evaluate as x^2+y^2 in the rest of your program, and in particular f(2,3)=13.

       This feature works by MATLAB parsing the single input string in the inline() function for strings of characters that are valid MATLAB variable names, which are an alphabetical character (a-z,A-Z) followed by alphanumeric characters (a-z,A-Z,0-9) up to the next non-alphanumeric character. Thus

    ff = inline('w77wombat^2 + b31z33^2')

    defines exactly the same function. Enter help inline or doc inline at the MATLAB command line for more information.

    
    
    7. Using MATLAB from a Command Prompt (or Console or Terminal) Window:
       If you want to run MATLAB so that it opens with a given directory (for example, c:\Temp) as its Current Directory, first open a Command-Prompt Window by clicking on

         Start | All Programs | Accessories | Command Prompt

    If the window opens with marginally-legible light-grey text on a black background, enter

         color F0

    (that is, ``color F-zero'') in the command-prompt window. You will now get legible black lettering on a parchment-white background in the Command-Prompt Window, exactly as in a Notepad window.

       Navigate to your directory of choice by using cd (``change directory'') commands in the command-prompt window. Then enter matlab at the command line. The program MATLAB will now appear with that directory as the Current Directory.

       You can call MATLAB from the command line to execute a particular program file and write the (Command-Window) output to a textfile by entering

         matlab   -r myfile.m   -logfile myoutputfile.txt

    MATLAB will run the program file myfile.m as soon as it loads and write the output to myoutputfile.txt. The program MATLAB will remain open, but can be closed in the usual way unless you want to use it further.
       The Windows batch file cmatlab.bat on the Math408 Web site automates this process. That is, enter cmatlab myfile to (i) load MATLAB, (ii) run myfile.m, and (iii) write Command-Window output to myfile.txt. The batch file cmatlab.bat includes options to make MATLAB run faster by not loading the full MATLAB GUI window, but does leave open a more primitive version of MATLAB, which you might still want to close.

    
    

  • Top of this page

    Last modified February 26, 2009