11.07.2015 Views

MatlabNotes

MatlabNotes

MatlabNotes

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.

This code resembles that given in Example 18.1.We have simply enclosed it in a function m–fileand given it the appropriate header. The mostsignificant change is the line F=zeros(1,n) whichserves to both define the value of F(1) and toallocate su cient memory to store a vector tohold the first n Fibonacci numbers. Had we notdone this then the length of the vector F wouldbe extended on each trip around the loop andmore memory would have to be allocated forits storage. The time penalties this would incurwould not be significant in this example (since,with modest values of n, it computes in a tinyfraction of a second) but could be importantwhen dealing with large arrays in codes thatare run many times over.Method 2: File Fib2.mThe first version was rather wasteful of memory,all the entries in the sequence where savedeven though we only required the last one foroutput. The second version removes the needto use a vector.function f = Fib2(n)% Returns the nth number in the% Fibonacci sequence.if n==1f = 0;elseif n==2f = 1;elsef1 = 0; f2 = 1;for i = 3:nf = f1 + f2;f1 = f2; f2 = f;endendMethod 3: File: Fib3.mThis version makes use of an idea called “recursiveprogramming”—the function makes callsto itself.function f = Fib3(n)% Returns the nth number in the% Fibonacci sequence.if n==1f = 0;elseif n==2f = 1;elsef = Fib3(n-1) + Fib3(n-2);endMethod 4: File Fib4.mThe final version uses matrix powers. apple The vectory has two components, y = .fnf n+1function f = Fib4(n)% Returns the nth number in the% Fibonacci sequence.A = [0 1;1 1];y = A^n*[1;0];f=y(1);Assessment: One may think that, on groundsof style, the 3rd is best (it avoids the use ofloops) followed by the second (it avoids the useof a vector). The situation is somewhat di↵erentwhen it comes to speed of execution. Whenn = 20 the time taken by each of the methodsis (in seconds)Method Time1 5.8052 ⇥ 10 52 2.5534 ⇥ 10 53 1.4972 ⇥ 10 14 5.4041 ⇥ 10 5What is immediately obvious from these timingsis that Method 3 is significantly slowerthan the others. Moreover, the time increasesdramatically as n is increased and is totally impractical.Methods 1, 2, and 4 execute veryrapidly and the times increase quite slowly asn is increased. When times are averaged overmany hundreds of runs it becomes clear thatMethod 2 is the most e cient followed by Method 1.23 Plotting SurfacesA surface is defined mathematically by a functionf(x, y)—corresponding to each value of (x, y)we compute the height of the function byz = f(x, y).36

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

Saved successfully!

Ooh no, something went wrong!