2011-09-28 47 views
0

中的前兩個變量我想寫一個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 
+0

您不能將索引歸零,請使用索引+1來訪問數組。 – Alex

回答

1

您的格式是有點過,但似乎像你分配一個值到一個數組中的零指數。據我所知,MatLab使用1作爲數組中第一項的索引。

如果您將if n>=2更改爲if >=3並設置1和2索引項目而不是0和1項目,則應該順利完成。

參見Is zero based indexing available in MATLAB

0

MATLAB使用基於1的索引,這意味着你應該重寫指數,以反映這種轉變,由N + 1次更換您的n個變量。這開始斐波那契在0,但索引到1,1,1,2,1在3,2在4,3在5,等到你的「n」項,現在被索引在n + 1。