Page 54 - Basics of MATLAB and Beyond
P. 54

i  =
                                    1
                                    2
                                    3
                               i  =
                                    1
                                    3
                                    6

                               Vectorised Code

                               matlab is a matrix language, and many of its algorithms are optimised
                               for matrices. matlab code can often be accelerated by replacing for
                               and while loops with operations on matrices. In the following example,
                               we calculate the factorial of the numbers from 1 to 500 using a for
                               loop. Create a script m-file called factorialloop.m that contains the
                               following code:

                               for number = 1:500
                                 fact = 1;
                                 for i = 2:number
                                   fact = fact*i;
                                 end
                                 y(number) = fact;
                               end
                               We can time how long this program takes to run by using the stopwatch
                               functions tic and toc:

                               >> tic;factorialloop;toc
                               elapsed_time   =
                                   4.6332
                               which is the time in seconds. The same calculation can be done in much
                               less time by replacing the internal for loop by the prod function. Create
                               an m-file called factorialvect.m:
                               for number = 1:500
                                 y(number) = prod(1:number);
                               end

                               This version takes about a tenth of the time:
                               >> clear
                               >> tic;factorialvect;toc
                               elapsed_time   =
                                   0.4331




                               c   2000 by CRC Press LLC
   49   50   51   52   53   54   55   56   57   58   59