Page 57 - A Guide to MATLAB for Beginners and Experienced Users
P. 57

38        Chapter 3: Interacting with MATLAB


                     Adding Comments. It is worthwhile to include comments in a lengthly script
                     M-file. These comments might explain what is being done in the calculation,
                     or they might interpret the results of the calculation. Any line in a script M-file
                     that begins with a percent sign is treated as a comment and is not executed by
                     MATLAB. Here is our new version of task1.m witha few comments added:

                       echo on
                       % Turn on 15 digit display
                       format long
                       x = [0.1, 0.01, 0.001];
                       y = sin(x)./x
                       % These values illustrate the fact that the limit of
                       % sin(x)/x as x approaches 0 is 1.
                       echo off
                     When adding comments to a script M-file, remember to put a percent sign at
                     the beginning of each line. This is particularly important if your editor starts
                     a new line automatically while you are typing a comment. If you use echo
                     on in a script M-file, then MATLAB will also echo the comments, so they will
                     appear in the Command Window.

                     Structuring Script M-Files. For the results of a script M-file to be reproducible,
                     the script should be self-contained, unaffected by other variables that you
                     might have defined elsewhere in the MATLAB session, and uncorrupted by
                     leftover graphics. With this in mind, you can type the line clear all at the
                     beginning of the script, to ensure that previous definitions of variables do
                     not affect the results. You can also include the close all command at the
                     beginning of a script M-file that creates graphics, to close all graphics windows
                     and start witha clean slate.
                       Here is our example of a complete, careful, commented solution to the
                     problem described above:

                       % Remove old variable definitions
                       clear all
                       % Remove old graphics windows
                       close all
                       % Display the command lines in the command window
                       echo on

                       % Turn on 15 digit display
                       format long
   52   53   54   55   56   57   58   59   60   61   62