Avoid two for loops in R

前端 未结 6 749
执念已碎
执念已碎 2021-02-08 11:15

I have a R code that can do convolution of two functions...

convolveSlow <- function(x, y) {  
nx <- length(x); ny <- length(y)  
xy <- numeric(nx          


        
6条回答
  •  粉色の甜心
    2021-02-08 11:49

    The convolveFast function can be optimized a little by carefully using integer math only and replacing (1:ny)-1L with seq.int(0L, ny-1L):

    convolveFaster <- function(x, y) {
        nx <- length(x)
        ny <- length(y)
        xy <- nx + ny - 1L
        xy <- rep(0L, xy)
        for(i in seq_len(nx)){
            j <- seq_len(ny)
            ij <- i + j - 1L
            xy[i+seq.int(0L, ny-1L)] <- xy[ij] + x[i] * y
        }
        xy
    }
    

提交回复
热议问题