通过矢量化提高速度

时间:2018-10-16 14:24:17

标签: r performance vectorization nested-loops

有人能帮助我改善此R函数的性能吗?我正在尝试使其尽快运行。

compile 'com.android.support:appcompat-v7:27.0.0'
compile 'com.android.support:support-v4:27.0.0'

谢谢!

1 个答案:

答案 0 :(得分:0)

向量化:

 stochrickvect <- 
function(p0=runif(1000,.5,1.5), r=1.2, K=1, sigma=0.2, numyears=100)
 {
   N <- matrix(NA, numyears, length(p0)) #initialize
   N[1,] <- p0

   for (yr in 2:numyears) # loop through the years
   {
     N[yr,] <- N[yr-1,]*exp(r*(1-N[yr-1,]/K) + rnorm(length(p0),0,sigma))
   }
   return(N)
 }