2015-02-24 56 views
1

我是新來的R,我嘗試解決一個遞歸函數:給予基於R解決遞歸函數

### creating variable R, a vector of length 10 
R = c(-1.70, 0.61, -0.54, -2.40, -1.50, -1.07, -2.42, -1.62, -1.65, -1.58) 

然後有一個模型:R[t] = A(t) + 0.5*A(t-1) + 0.3*A(t-2),其中A(0) = A(-1) = 0,然後計算A(i),我= 1,2 ... 10。我寫的代碼如下,但它總是給我錯誤,我不知道我錯了。 plz幫助我,非常感謝。

ma <- function(a){ 
        r = NULL 
        a = NULL 
        r[1]=1.70 
        r[2]=0.61 
        r[3]=-0.54 
        r[4]=-2.40 
        r[5]=-1.50 
        r[6]=-1.07 
        r[7]=-2.42 
        r[8]=-1.62 
        r[9]=-1.65 
        r[10]=-1.58 
        a[0] = 0 
        a[-1] = 0 
        for(i in 1:10){ 
        r[i]=a[i]+0.5*a[i-1]+0.3*a[i-2] 
        return(a[i]) 
        } 
       } 
+0

在R,數組的下標從1開始,則不能定義第0或一個陣列的-1th組件。此外,R並不解決方程式(或者至少不是你想象的方式):如果你想找到'a [i]',你需要在倒數第二行中解決'a [i]'。 – nicola 2015-02-24 06:29:43

+0

對不起,我不明白我需要在倒數第二行中解決它。謝謝 – user3084591 2015-02-24 06:34:34

+0

你需要在其他數量方面表達'a [i]'。看到我的答案。 – nicola 2015-02-24 06:39:20

回答

0

嘗試這種情況:

#define r with one call 
r<-c(1.7, 0.61, -0.54, -2.4, -1.5, -1.07, -2.42, -1.62, -1.65, -1.58) 
#initialize a with 12 values (its indices ranges from -1 to 10) 
a<-numeric(12) 
#set the first two elements of a to 0 
a[1:2]<-0 
#now solve for a[i], with i ranging from 3 to 12, corresponding to a_1,...,a_10 
for (i in 3:12) a[i]<-r[i-2]-0.5*a[i-1]-0.3*a[i-2] 
#get your values 
a[3:12] 
#[1] 1.7000000 -0.2400000 -0.9300000 -1.8630000 -0.2895000 -0.3663500 
#[7] -2.1499750 -0.4351075 -0.7874537 -1.0557409 
+0

非常感謝,所以我不需要定義一個函數:) – user3084591 2015-02-24 15:55:04

+0

還有一個問題,如果我寫這樣的代碼:'r [i-2] = a [i] + 0.5 * a [i-1 ] + 0.3 * a [i-2]',爲什麼結果全是零?謝謝 – user3084591 2015-02-24 19:32:12