I am doing the following operation with an array in the R:
> m <- matrix(1:9, ncol = 3, nrow = 3)
> m
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> m2 <- m
> for(i in 1:nrow(m)){
+ for(j in 1:ncol(m)){
+ c <- expand.grid((i-1):(i+1), (j-1):(j+1))
+ c <- c[c[,1] > 0 & c[,2]>0 & c[,1] <= nrow(m) & c[,2] <= ncol(m),]
+ m2[i,j] <- mean(m[c[,1], c[,2]])
+ }
+ }
> m2
[,1] [,2] [,3]
[1,] 3.0 4.5 6.0
[2,] 3.5 5.0 6.5
[3,] 4.0 5.5 7.0
That is, I am calculating for each element of the array the average of its adjacent elements.
However, my arrays are images and this method becomes very inefficient for large arrays ...
Does anyone know if there is any way to vectorize this loop?