An interactive introduction to MATLAB

(Jeff_L) #1

70 advanced topic: vectorisation


9 end
10 toc
11 Elapsed time is 6.876476 seconds.

Comments:


  • On Line 1 therandfunction is used to generate a matrix, 8000×8000,
    of uniformly distributed random numbers in the interval[0,1].

  • On Line 2 and Line 10 theticandtoccommands are used to time how
    long the code took to execute. Line 11 lists the result.


The code in Listing B.3 can be vectorised to produce the code given in
Listing B.4.
Listing B.4: Vectorisation of nested loops
1 data=rand(8000,8000);
2 tic
3 data(data<0.1)=0;
4 toc
5 Elapsed time is 0.927503 seconds.

Comments:


  • On Line 3 the nestedforloops have been replaced with a single line of
    vectorised code.data<0.1returns a matrix of 1’s and 0’s corresponding
    to values ofdataless than 0.1. The values of these elements are then set
    to 0.

  • Line 5 lists the time taken to execute the vectorised code. A difference
    of approximately 5 seconds may not seem like much of a speed increase,
    but in complexMATLABscripts with lots of loops performing many
    iterations it is can be significant.


Listings B.3–B.4 are an extreme example of vectorisation, but clearly demon-
strate thatMATLABcan execute vectorised code much faster than conven-
tional loops.
Free download pdf