title: Concatenation of numpy arrays of unknown dimension along arbitrary axis
body: <p>I have two arrays <code>A</code> and <code>B</code> of unknown dimensions that I want to concatenate along the <code>N</code>th dimension. For example:</p>
  
  <pre><code>&gt;&gt;&gt; A = rand(2,2)       # just for illustration, dimensions should be unknown
  &gt;&gt;&gt; B = rand(2,2)       # idem
  &gt;&gt;&gt; N = 5
  
  &gt;&gt;&gt; C = concatenate((A, B), axis=N)
  numpy.core._internal.AxisError: axis 5 is out of bounds for array of dimension 2
  
  &gt;&gt;&gt; C = stack((A, B), axis=N)
  numpy.core._internal.AxisError: axis 5 is out of bounds for array of dimension 3
  </code></pre>
  
  <p>A related question is asked <a href="https://stackoverflow.com/questions/8898471/concatenate-two-numpy-arrays-in-the-4th-dimension">here</a>. Unfortunately, the solutions proposed do not work when the dimensions are unknown and we might have to add several new axis until getting a minimum dimension of <code>N</code>.</p>
  
  <p>What I have done is to extend the shape with 1's up until the <code>N</code>th dimension and then concatenate:</p>
  
  <pre><code>newshapeA = A.shape + (1,) * (N + 1 - A.ndim)
  newshapeB = B.shape + (1,) * (N + 1 - B.ndim)
  concatenate((A.reshape(newshapeA), B.reshape(newshapeB)), axis=N)
  </code></pre>
  
  <p>With this code I should be able to concatenate a (2,2,1,3) array with a (2,2) array along axis 3, for instance.</p>
  
  <p>Are there better ways of achieving this?</p>
  
  <p>ps: updated as suggested the first answer.</p>