12.07.2015 Views

Basics of MATLAB and Beyond

Basics of MATLAB and Beyond

Basics of MATLAB and Beyond

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

time taken by this routine to calculate the pairwise sum <strong>of</strong> a 100,000-element vector (the code is saved in the m-file forloop1 <strong>and</strong> we useetime to measure the execution time):>>t0 = clock;forloop1;etime(clock,t0)ans =5.3545A little over five seconds. Now we try to do it another way. Here isa diagram <strong>of</strong> what we want to do, with the elements we want to sumwritten out as indices <strong>of</strong> the respective vectors:(a1 2 3 4 ... N − 2 N − 1)(+ a(= b2 3 4 5 ... N − 1 N1 2 3 4 ... N − 2 N − 1))Writing the operation in this way allows us to see how we can use vectors<strong>of</strong> indices to do the summation. The top line <strong>of</strong> the sum can be writtenin matlab notation as a(1:N-1), <strong>and</strong> the second line can be writtenas a(2:N). The pairwise sum vector b therefore can be calculated inmatlab 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 <strong>of</strong> thevector. This time there is no advantage in pre-allocating the b vectoras we did before the for loop above. With regular use, the vectorisedmatlab representation will seem to resemble the mathematical representationjust as closely as the for loop. The time taken by this codeist0 = clock;b = a(1:end-1) + a(2:end);etime(clock,t0)ans =2.2400The vectorised version runs a little more than twice as fast as thefor loop implementation.Looping over matrix or vector subscripts can <strong>of</strong>ten be replacedby such matrix operations. Appropriate matrices can be generatedusing subscripting, as here, or by rearranging the input matrices usingreshape, the transpose operator, or other matrix manipulations. matlab’scolumnar operations sum, diff, prod, etc. can then be used toc○ 2000 by CRC Press LLC

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!