Search code examples
arraysrconvolution

Convolution of a 2d array in one direction [R]


Is there any function in R to do the following procedure on a 2d array?

assume that I have an array like:

0    0    0    1    0    1
1    0    0    0    0    0
0    0    1    0    1    0
0    1    0    0    1    1

I want to do a linear convolution on this array in Horizontal direction, or with more detail I want a function to shift the array horizontally (with adding zeros) and dot product it to the main array and sum up all the elements of the resulting array.

so the result will be a linear vector

in this example the result will be:

0,2,1,2,1,9,1,2,1,2,0

for example, the second number which is 2, is the result of dot producting the main matrix with a copy of just 2 last columns as columns 1 and 2 (with other zero padding for the remaining columns) and sum all the resulting elements together:

0    0    0    1    0    1
1    0    0    0    0    0
0    0    1    0    1    0
0    1    0    0    1    1 

element-wise product to:

0    1    0    0    0    0
0    0    0    0    0    0
1    0    0    0    0    0
1    1    0    0    0    0  

results in:

0    0    0    0    0    0
0    0    0    0    0    0
0    0    0    0    0    0
0    1    0    0    0    0 

and finally by summing all elements it results in =2


Solution

  • There is no such function, but the main idea is quite straightforward:

    shift <- function(m) {
        cbind(m[, -1], rep(0, nrow(m)))
    }
    
    shifted_prod <- function(m) {
        mm <- m
        val <- numeric(ncol(m))
        for (i in 1:ncol(m)) {
            m <- shift(m)
            val[i] <- sum(m * mm)
        }
        val
    }
    
    shifted_prod(m)
    #[1] 1 2 1 1 0 0
    

    I still don't understand how you expect 2 as a result (element [4, 2] is 1, all others are 0). You can add print statements to watch the for loop step by step.

    You'll probably want something like rev(val) in the end (see for yourself), since right now val[k] is the result obtained by shifting the original matrix k times.