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

M-Files       39


                       % Define the vector of values of the independent variable
                       x = [0.1, 0.01, 0.001];


                       % Compute the desired values
                       y = sin(x)./x
                       % These values illustrate the fact that the limit of
                       % sin(x)/x as x approaches 0 is equal to 1.

                       echo off
                     Sometimes you may need to type, either in the Command Window or in an
                       M-file, a command that is too long to fit on one line. If so, when you get near
                       the end of a line you can type ... (that is, three successive periods) followed
                       by ENTER, and continue the command on the next line. In the Command
                       Window, you will not see a command prompt on the new line.


           Function M-Files

                     You often need to repeat a process several times for different input values of a
                     parameter. For example, you can provide different inputs to a built-in function
                     to find an output that meets a given criterion. As you have already seen, you
                     can use inline to define your own functions. In many situations, however,
                     it is more convenient to define a function using an M-file instead of an inline
                     function.
                       Let us return to the problem described above, where we computed some
                     values of sin(x)/x with x = 10 −b  for several values of b. Suppose, in addition,
                                                                               −b
                                                                                      −b
                     that you want to find the smallest value of b for which sin(10 )/(10 ) and 1
                     agree to 15 digits. Here is a function M-file called sinelimit.m designed to
                     solve that problem:

                       function y = sinelimit(c)
                       % SINELIMIT computes sin(x)/x for x = 10ˆ(-b),
                       % whereb=1, ..., c.
                       format long
                       b = 1:c;
                       x = 10.ˆ(-b);
                       y = (sin(x)./x)’;
                       Like a script M-file, a function M-file is a plain text file that should reside in
                     your MATLAB working directory. The first line of the file contains a function
   53   54   55   56   57   58   59   60   61   62   63