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.

i =i =123136Vectorised Codematlab is a matrix language, <strong>and</strong> many <strong>of</strong> its algorithms are optimisedfor matrices. matlab code can <strong>of</strong>ten be accelerated by replacing for<strong>and</strong> while loops with operations on matrices. In the following example,we calculate the factorial <strong>of</strong> the numbers from 1 to 500 using a forloop. Create a script m-file called factorialloop.m that contains thefollowing code:for number = 1:500fact = 1;for i = 2:numberfact = fact*i;endy(number) = fact;endWe can time how long this program takes to run by using the stopwatchfunctions tic <strong>and</strong> toc:>> tic;factorialloop;tocelapsed_time =4.6332which is the time in seconds. The same calculation can be done in muchless time by replacing the internal for loop by the prod function. Createan m-file called factorialvect.m:for number = 1:500y(number) = prod(1:number);endThis version takes about a tenth <strong>of</strong> the time:>> clear>> tic;factorialvect;tocelapsed_time =0.4331c○ 2000 by CRC Press LLC

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

Saved successfully!

Ooh no, something went wrong!