[R] Matrix-vector multiplication without loops

Richard Graham rickhg12hs at gmail.com
Thu Nov 16 05:43:47 CET 2006


On 11/14/06, Ravi Varadhan <rvaradhan at jhmi.edu> wrote:
> I am trying to do the following computation:
>
>       p <- rep(0, n)
>       coef <- runif(K+1)
>       U <- matrix(runif(n*(2*K+1)), n, 2*K+1)
>       for (i in 0:K){
>       for (j in 0:K){
>       p <- p + coef[i+1]* coef[j+1] * U[,i+j+1]
>       } }
>
> I would appreciate any suggestions on how to perform this computation
> efficiently without the "for" loops?

This kicks butt on my machine:

p <- as.vector(U %*% convolve(coef,rev(coef),type="open"))

HTH!

Richard Graham
JHU '84 EE&CS



More information about the R-help mailing list