title: Check the surrounding neighbors of a matrix element in Matlab
body: <p>I have a 480-by-640 matrix <code>A</code>. For each pixel, I want to check its neighbors. The neighbors of the pixel are determined by a value <code>N</code>. For example, this is a part of matrix <code>A</code> where all the zeros are the neighbours of pixel <code>X</code> when <code>N=3</code>:</p>
  
  <pre><code>0   0   0   0   0   0   0
  0   0   0   0   0   0   0
  0   0   0   0   0   0   0
  0   0   0   X   0   0   0
  0   0   0   0   0   0   0
  0   0   0   0   0   0   0
  0   0   0   0   0   0   0
  </code></pre>
  
  <p>As shown, because <code>N=3</code>, all these zeros are pixel <code>X</code>'s neighbors. The problem is if <code>X</code> is located before the index <code>N=3</code>. Here the neighbors will be pixels with one values:</p>
  
  <pre><code>    X   1   1   1   0   0   0
      1   1   1   1   0   0   0
      1   1   1   1   0   0   0
      1   1   1   1   0   0   0
      0   0   0   0   0   0   0
      0   0   0   0   0   0   0
      0   0   0   0   0   0   0
  </code></pre>
  
  <p>Could anyone advise on how to handle this?</p>