随机方程的循环

时间:2018-04-17 01:46:08

标签: r loops stochastic-process

我想使用以下表达式为100个不同的种子生成一系列随机方程:

set.seed(123)
N <- 100
  T <- 1
  x <- 10
  theta <- c (0 , 5 , 3.5)
  Dt <- 1 /N
  Y <- numeric (N +1)
  Y [1] <- x
  Z <- rnorm (N)
    for (i in 1: N)
    {Y[ i +1] <- Y[ i] + ( theta [1] - theta [2] * Y[ i ]) * Dt + theta [3] * sqrt ( Dt ) *Z [i ]
    Y <- ts (Y , start =0 , deltat =1 /N )

最后,我想保存100&#34; Y&#34;时间序列成矩阵。

如何创建一个保存&#34; Y&#34;的每个值的循环?时间序列?

1 个答案:

答案 0 :(得分:0)

如果你使用replicate作为代码的包装,我建议你需要在for - 循环之外添加对Y变量的附加引用。复制自然返回矩阵。使用10而不是100进行测试:

set.seed(123)
N=10
> rep.mtx <- replicate( 10, {
+   T <- 1
+   x <- 10
+   theta <- c (0 , 5 , 3.5)
+   Dt <- 1 /N
+   Y <- numeric (N +1)
+   Y [1] <- x
+   Z <- rnorm (N)
+     for (i in 1: N)
+     {Y[ i +1] <- Y[ i] + ( theta [1] - theta [2] * Y[ i ]) * Dt + theta [3] * sqrt ( Dt ) *Z [i ]
+     Y <- ts(Y , start =0 , deltat =1 /N ) } ; Y} )
> rep.mtx
            [,1]         [,2]        [,3]         [,4]        [,5]       [,6]       [,7]        [,8]       [,9]      [,10]
 [1,] 10.0000000 10.000000000 10.00000000 10.000000000 10.00000000 10.0000000 10.0000000 10.00000000 10.0000000 10.0000000
 [2,]  4.3796671  6.354810283  3.81813573  5.472009398  4.23110027  5.2803722  5.4201839  4.45652809  5.0063798  6.0996073
 [3,]  1.9350738  3.575646071  1.66781385  2.409420413  1.88542788  2.6085906  2.1541218 -0.32751756  2.9296172  3.6567678
 [4,]  2.6927109  2.231395747 -0.30167191  2.195432765 -0.45782317  1.2568464  0.7082679  0.94938979  1.0545631  2.0926115
 [5,]  1.4243939  1.238201192 -0.95757071  2.069632051  2.17168276  2.1431884 -0.7732224 -0.31024651  1.2404757  0.3513411
 [6,]  0.8552923  0.003897195 -1.17057706  1.944139651  2.42281031  0.8217115 -1.5728667 -0.91660925  0.3762039  1.6816368
 [7,]  2.3258752  1.979699020 -2.45211593  1.734254917 -0.03164826  2.0892811 -0.4504887  0.67679487  0.5553173  0.1764528
 [8,]  1.6730784  1.540869016 -0.29879763  1.480201956 -0.46173593 -0.6695147  0.2708330  0.02321148  1.4916370  2.5091604
 [9,] -0.5636270 -1.406211817  0.02035412  0.671577271 -0.74736079  0.3122915  0.1940814 -1.33948118  1.2274761  2.9508693
[10,] -1.0420203  0.073152826 -1.24950969 -0.002849978  0.48958280  0.2932273  1.1178037 -0.46907441  0.2529979  1.2145622
[11,] -1.0142676 -0.486707784  0.76296397 -0.422529220  0.15251875  0.3856172  2.8279298 -0.38826177  1.3979960 -0.5287587