title: Generate a matrix containing all combinations of elements taken from n vectors
body: <p>This question pops up quite often in one form or another (see for example <a href="https://stackoverflow.com/q/21804025/2586922">here</a> or <a href="https://stackoverflow.com/q/21867681/2586922">here</a>). So I thought I'd present it in a general form, and provide an answer which might serve for future reference.</p>
  
  <blockquote>
    <p>Given an arbitrary number <code>n</code> of vectors of possibly different sizes, generate an <code>n</code>-column matrix whose rows describe all combinations of elements taken from those vectors (Cartesian product) .</p>
  </blockquote>
  
  <p>For example,</p>
  
  <pre><code>vectors = { [1 2], [3 6 9], [10 20] }
  </code></pre>
  
  <p>should give</p>
  
  <pre><code>combs = [ 1     3    10
            1     3    20
            1     6    10
            1     6    20
            1     9    10
            1     9    20
            2     3    10
            2     3    20
            2     6    10
            2     6    20
            2     9    10
            2     9    20 ]
  </code></pre>