How to store a Fibonacci Sequence in an array using a for or a while loop?
15 次查看(过去 30 天)
显示 更早的评论
So I'm attempting to create a code that will allow the user to input any values they desire to find a fibonacci sequence with the user's desired number of elements for the sequence. I was able to get the sequence to produce values and work for any input. I'm now trying to take the outputs for the sequence and store it in an array using a for or a while loop, then I must display the Array. After displaying the array, I need to plot the results on a polar graph where the element number is the angle and the value of the element in the sequence is the radius. I'm running into trouble getting the output of the elements into an array and I would also like to display and plot it as stated above.
Here is what I have so far: x=input('Pick the first number of the sequence\n');
y=input('Pick the second number for the sequence\n');
k=input('Enter the total number of elements desired\n');
fib=zeros(1,x);
fib(1)=x;
fib(2)=y;
s=3;
while s<=k
fib(s)=fib(s-2)+fib(s-1);
s=s+1;
end
fprintf('The Fibonacci Sequence to %d terms is \n',k);
fprintf('%g ',fib);
fprintf('\n');
valueOffib=zeros(1,x);
for s=1:k
fib=fib(s);
valueOffib(s)=fib;
end
Here is the result and error that is occurring when I attempt to run the script:
Pick the first number of the sequence
1
Pick the second number for the sequence
2
Enter the total number of elements desired
5
The Fibonacci Sequence to 5 terms is
1 2 3 5 8
Attempted to access fib(2); index out of bounds because
numel(fib)=1.
0 个评论
回答(2 个)
Thorsten
2015-4-27
After the first while loop you already have the array with the values, namely fib. A Cartesian plot would be plot(1:k, fit), for a polar plot you can use polar(theta, fib), where theta are the angles in radians
theta = (1:k)/180*pi;
James Tursa
2015-4-27
You have a typo in your pre-allocation. zeros(1,x) should be zeros(1,k). I.e.,
fib=zeros(1,x);
should be
fib=zeros(1,k);
The for-loop doesn't make any sense because you already have the fibonacci sequence from the while-loop.
Also, it is not clear what you intend to plot. There is no "angle" associated with a single number. Did you mean to plot the angle associated with a point produced by grouping two successive numbers? And the "radius" maybe the ratio of two successive numbers? I.e., going after the Golden Ratio?
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!