MATLAB: Index exceeds array bounds help – Fibonacci Series

fibonacci serieshomeworkindex exceeds arra...MATLAB

Hi everyone. I'm doing an assignment (which needs to be handed in by tomorrow, so I hope to receive a quick help haha) and I have to calculate the golden ration from the Fibonacci Series.
The golden ration is defined as the division of the (N)th and the (N-1)th number of the Fibonacci Series. Here's my script:
clear;
close all;
clc;
% Input the value of N
n_2 = input('This script compute the golden ratio of the Nth and (Nth - 1)th Fibonacci numbers. Enter the value of N.\nN = ');
n_1 = n_2 - 1;
% Find the Fibonacci Series values
fibonacci(1) = 1;
fibonacci(2) = 1;
for i = 3:n_2
fibonacci(i) = fibonacci(i-1) + fibonacci(i-2);
if i >= 4
fibonacci(i-3) = []
end
end
golden_ratio = fibonacci(n_2)/fibonacci(n_1);
% Print results
fprintf('\nThe golden ration between the %.fth and the %.fth number of the Fibonacci series is %f', n_2, n_1, golden_ratio)
Obviously I can't use the fibonacci function. Also, the assignment ask to "save space": each term of the Fibonacci Series is computed using the two previous terms. For this reason, since at the end we only need the (N)th and (N-1)th terms, we can delete all the other ones as the loop goes. I tried to do this here:
if i >= 4
fibonacci(i-3) = []
end
And here's the problem. The script, without these three line, does work and does give the value of the golden ratio. As soon as I try to implement the "saving-space" lines, I get the error:
Index exceeds array bounds.
Error in Copy_of_PS_3 (line 18)
fibonacci(i) = fibonacci(i-1) + fibonacci(i-2);
How can I fix this? Any help is appreciated. Thank you!

Best Answer

When you delete something out of the fibonacci variable, MATLAB does not just leave a "hole" not occupied by storage: MATLAB causes the elements afterwards to "fall down" to fill the hole.
For example, if you have 1 2 3 4 5 and you delete the third element, then what you get is not 1 2 (hole) 4 5: it would instead be 1 2 4 5
Hint:
old = 149;
for K = 1 : 20
if ~mod(old, 2)
current = old/2;
else
current = old * 3 + 1;
end
disp(current);
old = current;
end