[英]More efficient matrix operation in R
I am trying to compute the convolution of two discrete probability distributions in R. I have two vectors, each containing the probabilities. 我正在尝试计算R中两个离散概率分布的卷积。我有两个向量,每个向量都包含概率。 I need to compute a third vector, which has the combined probabilities of the previous two vectors.
我需要计算第三个向量,该向量具有前两个向量的组合概率。 The ith position in the third vector contains the sum of probabities (a[j]*b[k]) for all j+k=i.
第三个向量中的第i个位置包含所有j + k = i的概率之和(a [j] * b [k])。 I have the following function for doing this:
我具有以下功能:
convolute <- function(a, b ){
out <- rep(0, (length(a)+741))
for(i in 1:length(a)){
for (j in 1:length(b)){
out[i + j] <- out[i+j] + (a[i]*b[j])
}
}
return(out)
}
My problem is that this function needs to be called multiple times (>1000000) and is (relatively) slow. 我的问题是,此函数需要多次调用(> 1000000),并且(相对)缓慢。 Is there an more efficient way in R to achieve this operation, without using the two for loops?
R中是否有更有效的方法来实现此操作,而无需使用两个for循环? The length of a will either be 741 or 1482, b is always 741.
a的长度可以是741或1482,b总是741。
Thank you 谢谢
convolve(a, rev(b), type="open")
Does the same as your function, except that your function starts with a 0 and convolve
doesn't: 与您的函数相同,但函数以0开头且
convolve
不起作用:
> a <- runif(1000, 0, 1)
> b <- runif(741, 0, 1)
> c1 <- convolute(a, b)
> c2 <- convolve(a, rev(b), type="open")
>
> all.equal(c1[-1], c2)
[1] TRUE
> system.time(c1 <- convolute(a, b))
user system elapsed
4.152 0.000 4.155
> system.time(c2 <- convolve(a, rev(b), type="open"))
user system elapsed
0.000 0.000 0.001
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.