Concatenation of numpy arrays of unknown dimension along arbitrary axis
This should work:
def atleast_nd(x, n): return np.array(x, ndmin=n, subok=True, copy=False)np.concatenate((atleast_nd(a, N+1), atleast_nd(b, N+1)), axis=N)
An alternative, using numpy.expand_dims:
>>> import numpy as np>>> A = np.random.rand(2,2)>>> B = np.random.rand(2,2)>>> N=5>>> while A.ndim < N: A= np.expand_dims(A,x)>>> while B.ndim < N: B= np.expand_dims(B,x)>>> np.concatenate((A,B),axis=N-1)
I don't think there's anything wrong with your approach, although you can make your code a little more compact:
newshapeA = A.shape + (1,) * (N + 1 - A.ndim)