# I'm trying to plot the golden ratio to show that it converges

9 views (last 30 days)
ray sanchez on 9 Apr 2015
Answered: Juan Sierra on 4 Sep 2020
I'm trying to write a matlab script that displays the fibonacci sequence and plots the ratio of succesive members of the series (the golden ratio), 1/1=1; 2/1=2; 3/2=1.5 etc. I already figured out the code to display the fibonacci sequence. I just don't know how to plot the ratio. Here is my code I have so far.
%code
f=[1 1];
x=1;
while f(x) < 10000
f(x+2)=f(x+1)+f(x);
x=x+1;
end
f

James Tursa on 9 Apr 2015
Edited: James Tursa on 9 Apr 2015
Just add a line to calculate the ratio at each step. E.g.,
Initialize prior to the loop:
f_ratio = [1 1];
f_ratio(x+2) = f(x+2)/f(x+1);
Then after the loop:
plot(f_ratio);
ray sanchez on 9 Apr 2015
That worked. Thanks!

John D'Errico on 9 Apr 2015
Edited: John D'Errico on 9 Apr 2015
I tend not to answer homework questions. But here I see someone who has some decent code, and was willing to show it. Well done. :)
There are few things I would suggest changing with that code, at least in terms of writing the sequence as a loop.
The one thing I would suggest adding are comments. They help you to read the code, to debug it, or for your colleague to read/use/debug it one day when you get run down by the cross-town bus. Admittedly, this is a short code, but don't forget to add those internal comments when your code starts getting more complex. I like to suggest at least one comment every few lines, explaining what a specific block of code does.
As James has suggested, you can just compute the ratio of terms inside the loop. Or you can get tricky, and after the while loop is complete, you can use a vectorized form:
f_ratio = exp(diff(log(f)));
One other point - you did not preallocate the vector f. The problem is that as f grows larger, MATLAB must reallocate the memory for it after every iteration, growing that array. For small enough vectors, nothing matters, but this is an operation that grows quadratically with time. So if your vector was expected to be pretty long, then it will take a moderately long time to do. In fact, this is perhaps one of the biggest reasons people ask for help on the group to speed up their code. I'e., they did NOT preallocate a vector.
In your case, you do not "know" how large that n'th Fibonacci number is, or how long the vector will be at the end, so preallocation will be a problem there. My point is though, whenever you can, try to avoid growing vectors and arrays like that using dynamic reallocations in a loop. Sometimes you cannot avoid it. But do try.

Juan Sierra on 4 Sep 2020
Probably previous answers are the way to go. However, I thought this one was pretty cool!
N = 1475; %Largest fib num in double precision
f = impz(1, [1, -1, -1], N); %Impulse response of difference equation representing fib!
fRatio = exp(diff(log(f)));
plot(fRatio);