中的前兩個變量我想寫一個MatLab函數來計算斐波那契數。下面是我所擁有的,但是它出現了一個關於F(0)
的錯誤。MatLab只分配
??? Attempted to access F(0); index must be a positive integer or logical.
Error in ==> fibonacci at 11
F(0) = 0;
我如何告訴MATLAB數組中的前兩個值是0和1?
function F = fibonacci(n)
%A fibonacci sequence is where the next term in the series is given by the
%sum of the pervious two terms
%Only valid if n is greater than or equal to 2
if n >= 2 ;
%Make an array with n terms
F = zeros (1,n);
%run a for loop from 2 to n
for i = 2:n;
F(0) = 0;
F(1) = 1;
F(i) = F(i-1) + F(i-2)
end
end
end
您不能將索引歸零,請使用索引+1來訪問數組。 – Alex