title: Fastest solution to list all pairs of n integers?
body: <p>I want to list all possible pairs of the integers <code>[1, n]</code> with a large <code>n</code>. I find myself looking for the fastest option. This is what I've come up with so far. </p>
  
  <p>Matlab's <a href="http://www.mathworks.com/help/matlab/ref/nchoosek.html" rel="nofollow"><code>nchoosek</code></a> and <a href="http://www.mathworks.com/help/stats/combnk.html?searchHighlight=combnk" rel="nofollow"><code>combnk</code></a> methods recommend <code>n&lt;15</code> for listing all possible combinations because of the explosive number of combinations. So how fast this is depends on the n.</p>
  
  <pre><code>pair = nchoosek(1:n, 2);
  </code></pre>
  
  <p>Another option would be to use a nested for loop</p>
  
  <pre><code>kk =1;
  pair = zeros(nchoosek(n, 2), 2);
  for ii = 1:n
      for jj = ii+1:n
          pair(kk, :) = [ii, jj];
          kk = kk + 1;
      end
  end  
  </code></pre>
  
  <p>This would be relatively slow. </p>
  
  <p>I also thought of using the <code>ind2sub</code> function directly</p>
  
  <pre><code>pair_adjacency = tril(ones(n),  -1);
  [x, y] = ind2sub(size(pair_adjacency), find(pair_adjacency==1)); 
  pair = [x, y];
  </code></pre>
  
  <p>Timing these methods in a loop, 10 times each with <code>n=1000</code>, I get fastest to slowest</p>
  
  <ol>
  <li>ind2sub (0.15 sec)</li>
  <li>for loop (16.3 sec)</li>
  <li>nchoosek (16.8 sec)</li>
  </ol>
  
  <p>It seems like <code>ind2sub</code> is the fastest way to go by a long shot. Just out of curiosity, what are other options that may or may not be faster?</p>