title: Construct adjacency matrix in MATLAB
body: <p>Consider a set of points arranged on a grid of size N-by-M.
  I am trying to build the adjacency matrix such that
  neighboring points are connected.</p>
  
  <p>For example, in a 3x3 grid with a graph:</p>
  
  <pre><code>1-2-3
  | | |
  4-5-6
  | | |
  7-8-9
  </code></pre>
  
  <p>We should have the corresponding adjacency matrix:</p>
  
  <pre><code>+---+------------------------------------------------------+
  |   |   1     2     3     4     5     6     7     8     9  |
  +---+------------------------------------------------------+
  | 1 |   0     1     0     1     0     0     0     0     0  |
  | 2 |   1     0     1     0     1     0     0     0     0  |
  | 3 |   0     1     0     0     0     1     0     0     0  |
  | 4 |   1     0     0     0     1     0     1     0     0  |
  | 5 |   0     1     0     1     0     1     0     1     0  |
  | 6 |   0     0     1     0     1     0     0     0     1  |
  | 7 |   0     0     0     1     0     0     0     1     0  |
  | 8 |   0     0     0     0     1     0     1     0     1  |
  | 9 |   0     0     0     0     0     1     0     1     0  |
  +---+------------------------------------------------------+
  </code></pre>
  
  <p>As a bonus, the solution should work for both 4- and 8-connected neighboring points, that is:</p>
  
  <pre><code>   o             o  o  o
  o  X  o   vs.    o  X  o
     o             o  o  o
  </code></pre>
  
  <p>This the code that I have so far:</p>
  
  <pre><code>N = 3; M = 3;
  adj = zeros(N*M);
  
  for i=1:N
      for j=1:M
          k = sub2ind([N M],i,j);
          if i&gt;1
              ii=i-1; jj=j;
              adj(k,sub2ind([N M],ii,jj)) = 1; 
          end
          if i&lt;N
              ii=i+1; jj=j;
              adj(k,sub2ind([N M],ii,jj)) = 1; 
          end
          if j&gt;1
              ii=i; jj=j-1;
              adj(k,sub2ind([N M],ii,jj)) = 1; 
          end
          if j&lt;M
              ii=i; jj=j+1;
              adj(k,sub2ind([N M],ii,jj)) = 1; 
          end
      end
  end
  </code></pre>
  
  <p>How can this improved to avoid all the looping?</p>