Page 32 - MATLAB Recipes for Earth Sciences
P. 32

2.6 Scripts and Functions                                        23

             Name      Size                    Bytes  Class
             ans       1x1                         8  double array
             m         1x1                         8  double array
             n         1x1                         8  double array
             x         1x5                        40  double array
             Grand total is 8 elements using 64 bytes
           The listed variables are the example vector x and the output of the size
           function, m and n. The result of the operation is contained in the variable
           ans. Since the default variable ans might be overwritten during one of the
           following operations, we wish to define a different variable. Typing

             a = average
           however, causes the error message

             ??? Attempt to execute SCRIPT average as a function.

           Obviously, we cannot assign a variable to the output of a script. Moreover,

           all variables defined and used in the script appear in the workspace, in our
           example, the variables  m and  n. Scripts contain sequences of commands
           applied to variables in the workspace. MATLAB functions instead allow to

           define inputs and outputs. They do not automatically import variables from
           the workspace. To convert the above script into a function, we have to intro-

           duce the following modifications (Fig. 2.3):
             function y = average(x)
             %AVERAGE    Average value.
             %    AVERAGE(X) is the average of the elements in the vector X.
             % By Martin Trauth, Feb 18, 2005.

             [m,n] = size(x);
             if m == 1
                m = n;
             end
             y = sum(x)/m;
           The first line now contains the keyword function, the function name
           average and the  input x and  output y. The next two lines contain  com-
           ments as indicated by the percent sign. After one empty line, we see an-
           other  comment line containing informations on the author and version of the
           M-fi le. The remaining fi le contains the actual operations. The last line now
           defi nes the value of the output variable y. This line is now terminated by a
           semicolon to suppress the display of the result in the Command Window.
           We fi rst type
             help average
   27   28   29   30   31   32   33   34   35   36   37