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

M-Files       37


           Script M-Files
                     We now show how to construct a script M-file to solve the mathematical prob-
                     lem described earlier. Create a file containing the following lines:
                       format long
                       x = [0.1, 0.01, 0.001];
                       y = sin(x)./x
                     We will assume that you have saved this file with the name task1.m in your
                     working directory, or in some directory on your path. You can name the file
                     any way you like (subject to the usual naming restrictions on your operating
                     system), but the “.m” suffix is mandatory.
                       You can tell MATLAB to run (or execute) this script by typing task1 in
                     the Command Window. (You must not type the “.m” extension here; MATLAB
                     automatically adds it when searching for M-files.) The output — but not the
                     commands that produce them — will be displayed in the Command Window.
                     Now the sequence of commands can easily be changed by modifying the M-file
                     task1.m. For example, if you also wishto calculate sin(0.0001)/0.0001, you
                     can modify the M-file to read

                       format long
                       x = [0.1, 0.01, 0.001, 0.0001];
                       y = sin(x)./x
                     and then run the modified script by typing task1. Be sure to save your
                     changes to task1.m first; otherwise, MATLAB will not recognize them. Any
                     variables that are set by the running of a script M-file will persist exactly
                     as if you had typed them into the Command Window directly. For example,
                     the program above will cause all future numerical output to be displayed
                     with15 digits. To revert to 5-digit format, you would have to type format
                     short.

                     Echoing Commands. As mentioned above, the commands in a script M-file
                     will not automatically be displayed in the Command Window. If you want the
                     commands to be displayed along withthe results, use echo:

                       echo on
                       format long
                       x = [0.1, 0.01, 0.001];
                       y = sin(x)./x
                       echo off
   51   52   53   54   55   56   57   58   59   60   61