Page 188 - Basics of MATLAB and Beyond
P. 188

time taken by this routine to calculate the pairwise sum of a 100,000-
                               element vector (the code is saved in the m-file forloop1 and we use
                               etime to measure the execution time):
                               >>t0 = clock;forloop1;etime(clock,t0)
                               ans  =
                                   5.3545

                               A little over five seconds. Now we try to do it another way. Here is
                               a diagram of what we want to do, with the elements we want to sum
                               written out as indices of the respective vectors:


                                      a    1     2     3    4    ...      N − 2   N − 1


                                  +   a    2     3     4    5    ...      N − 1     N



                                  =   b    1     2     3    4    ...     N − 2    N − 1

                               Writing the operation in this way allows us to see how we can use vectors
                               of indices to do the summation. The top line of the sum can be written
                               in matlab notation as a(1:N-1), and the second line can be written
                               as a(2:N). The pairwise sum vector b therefore can be calculated in
                               matlab with the following code:
                               b = a(1:end-1) + a(2:end);

                               We have used the special index end to refer to the final element of the
                               vector. This time there is no advantage in pre-allocating the b vector
                               as we did before the for loop above. With regular use, the vectorised
                               matlab representation will seem to resemble the mathematical repre-
                               sentation just as closely as the for loop. The time taken by this code
                               is

                               t0 = clock;b = a(1:end-1) + a(2:end);etime(clock,t0)
                               ans  =
                                   2.2400
                               The vectorised version runs a little more than twice as fast as the
                               for loop implementation.
                                  Looping over matrix or vector subscripts can often be replaced
                               by such matrix operations.  Appropriate matrices can be generated
                               using subscripting, as here, or by rearranging the input matrices using
                               reshape, the transpose operator, or other matrix manipulations. mat-
                               lab’s columnar operations sum, diff, prod, etc. can then be used to




                               c   2000 by CRC Press LLC
   183   184   185   186   187   188   189   190   191   192   193