-2

我的代码块正在做的是用 F 中的 T 填充一个 4X100000 矩阵。让我们将矩阵命名为 X。然后是 Xij ~ Bernoulli(P) 和 P~normal(0.5,0.15) 其中 max(P) = 1 和最小(P)= 0。

该统计数据非常低效。如果有上述过程遵守的发行版,请也帮助我。

计算非常慢,因为我必须用 1 个条目填充整个矩阵 1 个条目,每次都是随机的。有没有办法显着减少花费的时间?这是非常低效的。

这里的统计效率问题

x = rnorm(100000,mean = 0.5,sd = 0.15)
x[x > 1] = 1
x[x < 0] = 0

probability = function(x){
  x.sam = sample(x,1)
  p = c(x.sam,1-x.sam)
  return(p)
}

aggro2 = function(x){
  aggro2 = sample(c(T,F),1, prob = probability(x))
  return(aggro2)
}

这里的计算效率问题

ptm = proc.time()
aggro =c()
n=100000
for (i in 1:(4*n)){
  cat(round(i/(4*n)*100,2),"\n")
  aggro = c(aggro, aggro2(x))  
}
aggro.mat = matrix(aggro,4,n)

elapsed = proc.time()[3] - ptm[3]
cat(elapsed)
4

1 回答 1

7

How about this?

system.time({
    x <- rnorm(400000,mean = 0.5,sd = 0.15)  ## pick normal variables
    x2 <- pmin(1,pmax(0,x))                  ## bound at 0 and 1
    mids <- which(x2>0 & x2<1)
    x2[mids] <- rbinom(length(mids),prob=x2[mids],size=1)  
    res <- matrix(x2,ncol=4)
})

This doesn't seem to be exactly the same as what you're doing, but it seems (?) to match your description.

elapsed time: 0.443 seconds

Several of the things that you're doing will be unnecessarily slow:

  • using a for loop instead of vectorizing
  • creating a vector by appending instead of allocating the whole vector and then replacing elements
  • printing in the course of the for loop
于 2013-05-25T14:50:45.183 回答