1

我正在尝试对大量参数组合进行简单计算。我有 15,625 个排列,并且想为每个组合运行蒙特卡洛实验(~5000)。我的问题是正确存储数据并避免永远占用的 for 循环。我想使用应用功能,但无法弄清楚。我有以下代码,它可以运行,但效率很低!我有兴趣保存“res [i,j]”值。我已经看到进行蒙特卡洛的一种简单方法是使用复制命令……但显然我还没有……任何建议将不胜感激!

#run the beta function
beta <- function(M) {
  b_slope <- log(M) / 10
  return (b_slope)
}
#set the experiment conditions for looping through different M, Cv, and q parameter vals
cvVals <- seq(0.1,3.09,0.12)
mVals <- seq(1,2.98,0.08)
qVals <- seq(0.9,0.999,0.004)
mNum <- length(mVals);cvNum <- length(cvVals);qNum<-length(qVals);
total<-mNum*cvNum*qNum

#iterate through time (up to 5000 yrs)
imax<-5000

#Number of experiments
expts<-5

#fill a matrix with each combination of cv, m, q values
df <- data.frame(expand.grid(cv=cvVals, m=mVals, q=qVals))

#set a column in the df to have X_Crit values
df$i<-seq(1:nrow(df))
df$X_crit <- qlnorm(df$q)

#store the results in a df with the dimensions of df by # of experiments
res <- data.frame(nrow=nrow(df), ncol=expts)

for (i in 1:nrow(df)) {

  for (j in 1:ncol(res)) {
    #fill in all the x_critical values for each q
    X_crit <- df$X_crit[i]

    #compute the mean and std dev and flow for all values up to imax
    tempmean <- beta(df$m[i])*seq(0, imax-1)
    tempstd <- df$cv[i]*tempmean
    #generate imax random lognorm variables as error terms 
    err <- rlnorm(imax, 0, 1)
    #compute flow from lognormal quantile function
    flow <- tempmean + tempstd*err

    #store the result which looks for the first exceedance of flow 
    if (sum(flow>X_crit)>0) {
      res[i, j] <-min(which(flow > X_crit))
    } else {
      res[i,j] <- imax
    }

  }

}
4

1 回答 1

0

只需删除 for j 循环。它似乎没有任何目的

于 2016-09-04T13:21:23.993 回答