title: Fastest way to apply a filter to a matrix in R
body: <p>If I have a 2d matrix and I would like to apply some sort of filter (e.g. dilate, erode, sobel edge detection) given some filter matrix:</p>
  
  <pre><code>f = matrix(c(0,1,0,
               1,1,1,
               0,1,0), 3)
  </code></pre>
  
  <p>What is the most efficient way to apply it to a matrix. </p>
  
  <p>For looping over each pixel seems too inefficient:</p>
  
  <pre><code>for(i in 2:nrow(mat)){
      for(j in 2:ncol(mat)){
          //Apply filter to pixel i,j
      }
  }
  </code></pre>