MATLAB: How to sum up elements in Fibonnaci sequence

fibbonacifor loop

This is my code and I would want to summ up all iterations in for loop from i==3:n but I dont know can I do this on this way?
function [total]=fibonaci(n)
if isscalar(n)||n<1||n~=fix(n)
false
end
f(1)=1;
f(2)=1;
for ii=3:n
f(ii)=f(ii-2)+f(ii-1);
summ=f(ii)+f(ii-1)
end

Best Answer

Well, you DID make an effort. And it is not even that bad an effort at that. I'm willing to help when someone makes a serious effort.
I think you anted to generate an error here if the test shows a problem. Yet false does not do that.
if isscalar(n)||n<1||n~=fix(n)
false
end
Instead, you might use the error function.
if isscalar(n)||n<1||n~=fix(n)
error('The sky is falling! There is a problem with n.')
end
Next, you should preallocate the vector f, since you know how long it will be in the end. That will make your code more efficient.
Finally, your summation has a problem, in that you are not accumulating the sum properly. As well you compute the sum as summ, but then you return a variable named total. So initialize summ before the loop starts, then accumulate into summ.
And, by the way, you misspelled fibbonacci. :)
function summ = fibbonacci(n)
if isscalar(n)||n<1||n~=fix(n)
error('The sky is falling! There is a problem with n.')
end
f = zeros(1,n); % preallocating f

f(1)=1;
f(2)=1;
summ = f(1) + f(2); % initialize with the first two elements

for ii=3:n
f(ii)=f(ii-2)+f(ii-1);
summ = summ + f(ii);
end
You were pretty close though. Note that the above code will fail when n=1 though, since it always includes the first two elements in that summation. So better code will worry about that event. Still trying to stay as close to your original code as I can, I might do it as:
function summ = fibbonacci(n)
if isscalar(n)||n<1||n~=fix(n)
error('The sky is falling! There is a problem with n.')
end
f = zeros(1,n); % preallocating f
f(1)=1;
f(2)=1;
if n == 1
% just bounce out here after we compute
% summ, since we are all done when n==1
summ = f(1);
return
else
summ = f(1) + f(2); % initialize with the first two elements
for ii=3:n
f(ii)=f(ii-2)+f(ii-1);
summ = summ + f(ii);
end
end
this version traps for the special case of n==1.
By the way, I'll give you extra credit for using the names summ and ii as variables, avoiding use of sum and i.