Page 33 - MATLAB Recipes for Earth Sciences
P. 33

24                                            2 Introduction to MATLAB






















            Fig. 2.3 Screenshot of the MATLAB  Text Editor showing the function  average. The
            function starts with a line containing the keyword function, the name of the function
            average and the input variable x and the output variable y. The following lines contain
            the output for help average, the copyright and version information as well as the actual
            MATLAB code for computing the average using this function.





            which displays the first block of contiguous comment lines. The fi rst execut-
            able statement or blank line — as in our example — effectively ends the
            help section and therefore the output of help. Now we are independent from
            the variable names used in our function. We clear the workspace and defi ne
            a new data vector.

               clear
               data = [3 6 2 -3 8];

            We run our function by the statement

               result = average(data);
            This clearly illustrates the advantages of functions compared to scripts.
            Typing

               whos
            results in

               Name         Size                    Bytes  Class
               data         1x5                        40  double array
               result       1x1                         8  double array
               Grand total is 6 elements using 48 bytes
   28   29   30   31   32   33   34   35   36   37   38