Reputation: 1
I want to create a function that starts off with the first two elements in an array, and then creates the Fibonacci sequence from them, but it creates a weird matrix with decimals and such, and it's twice the number of columns I want every time. When I looked it up, this is what I came up with after struggling through the documentation.
I have almost no experience with MATLAB, and I'm used to python. I haven't been able to find anything that really addresses my problem. Or helps.
function [f,s] = fibb(nmax)
f = array(1,0);
% first two items in array are 0 and 1 respectively
for n = 3 : 1 : nmax
f(n) = [f(n-1) + f(n-2) newElem];
% Adds new entry, entry is sum of previous two
end
s = sum(f);
% sum of the sequence
Upvotes: 0
Views: 30
Reputation: 58
As an addition to what RPM wrote, I would suggest that you preallocate your f vector to make it work a bit faster. Just substitute the f = [1,1]
command with the one below:
f = ones(1,nmax);
Otherwise matlab has to dynamically increase the size of your vector in each loop, making your function slower.
Upvotes: 0
Reputation: 1769
array
is not an in-built function in Matlab. Also, a Fibonacci sequence starts with [1,1]
.
Try the following:
function [f,s] = fibb(nmax)
f = [1,1];
for n = 3 : nmax
f(n) = f(n-1) + f(n-2);
end
s = sum(f);
end
There is probably a more efficient approach, but this should be a working version of your code.
Upvotes: 0