title: Matlab: Find the distance from an element to the matrix border
body: <p>Say in Matlab I have a matrix like this:</p>
  
  <pre><code>1 2 3 4 5 6 7 8 9
  1 2 3 4 5 6 7 8 9
  1 2 3 4 5 6 7 8 9
  1 2 3 4 5 6 7 8 9
  1 2 3 4 5 6 7 8 9
  1 2 3 4 5 6 7 8 9
  </code></pre>
  
  <p>I now need to find submatrixes 3x3 around every element (so each element in turn is the center of a 3x3 submatrix). When in the middle, it is no problem to find fx </p>
  
  <p>1 2 3 4 5 6 7 8 9<br>
  1 <strong>2 3 4</strong> 5 6 7 8 9<br>
  1 <strong>2 3 4</strong> 5 6 7 8 9<br>
  1 <strong>2 3 4</strong> 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9</p>
  
  <p>which is the submatrix:</p>
  
  <pre><code>2 3 4
  2 3 4
  2 3 4
  </code></pre>
  
  <p>But when in the border of the matrix, that is elements in the first og last row or column, it of course isn't possible to find a 3x3 submatrix. Instead I need the submatrix that fits. In the corner fx I would get </p>
  
  <p><strong>1 2</strong> 3 4 5 6 7 8 9<br>
  <strong>1 2</strong> 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9  </p>
  
  <p>where the submatrix is:</p>
  
  <pre><code>1 2
  1 2
  </code></pre>
  
  <p>and in the middle of the border, I get fx:</p>
  
  <p>1 2 3 <strong>4 5 6</strong> 7 8 9<br>
  1 2 3 <strong>4 5 6</strong> 7 8 9<br>
  1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9</p>
  
  <p>which gives:</p>
  
  <pre><code>4 5 6
  4 5 6
  </code></pre>
  
  <p>or as another example:</p>
  
  <p>1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 6 7 8 9<br>
  1 2 3 4 5 <strong>6 7 8</strong> 9<br>
  1 2 3 4 5 <strong>6 7 8</strong> 9</p>
  
  <p>which gives:</p>
  
  <pre><code>6 7 8
  6 7 8
  </code></pre>
  
  <p>I hope you understand my point. I am missing some feature that lets me find the distance from an element to the border.</p>
  
  <p>I can treat every element as a center of a submatrix, and if I can just test, if the distance from the element to the border is below the submatrix's border (the submatrix dimension will namely change, to fx a 5x5 submatrix), then I can truncate a part of the submatrix while it is being made.</p>
  
  <p>How do I find the distance from an element to the border of the matrix in the most efficient way?</p>