1

I'm trying to concatenate 2 arrays element wise. I have the concatenation working to produce the correct shape but it has not been applied element wise.

So i have this array

[0, 1]
[2, 3]
[4, 5]

I want to append each element in the array with each element. the target result would be

[0, 1, 0, 1]
[0, 1, 2, 3]
[0, 1, 4, 5]
[2, 3, 0, 1]
[2, 3, 2, 3]
[2, 3, 4, 5]
[4, 5, 0, 1]
[4, 5, 2, 3]
[4, 5, 4, 5] 

i think i may need to change an axis but then i can't get the broadcasting to work.

any help would be greatly appreciated. lots to learn in numpy !

a = np.arange(6).reshape(3, 2))
b = np.concatenate((a, a), axis=1)
user1305541
  • 205
  • 1
  • 4
  • 14

2 Answers2

2

One way would be stacking replicated versions created with np.repeat and np.tile -

In [52]: n = len(a)

In [53]: np.hstack((np.repeat(a,n,axis=0),np.tile(a,(n,1))))
Out[53]: 
array([[0, 1, 0, 1],
       [0, 1, 2, 3],
       [0, 1, 4, 5],
       [2, 3, 0, 1],
       [2, 3, 2, 3],
       [2, 3, 4, 5],
       [4, 5, 0, 1],
       [4, 5, 2, 3],
       [4, 5, 4, 5]])

Another would be with broadcasted-assignment, since you mentioned broadcasting -

def create_mesh(a):
    m,n = a.shape
    out = np.empty((m,m,2*n),dtype=a.dtype)
    out[...,:n] = a[:,None]
    out[...,n:] = a
    return out.reshape(-1,2*n)
Divakar
  • 218,885
  • 19
  • 262
  • 358
1

One solution is to build on senderle's cartesian_product to extend this to 2D arrays. Here's how I usually do this:

# Your input array.
arr    
# array([[0, 1],
#        [2, 3],
#        [4, 5]])

idxs = cartesian_product(*[np.arange(len(arr))] * 2)
arr[idxs].reshape(idxs.shape[0], -1)    
# array([[0, 1, 0, 1],
#        [0, 1, 2, 3],
#        [0, 1, 4, 5],
#        [2, 3, 0, 1],
#        [2, 3, 2, 3],
#        [2, 3, 4, 5],
#        [4, 5, 0, 1],
#        [4, 5, 2, 3],
#        [4, 5, 4, 5]])
cs95
  • 379,657
  • 97
  • 704
  • 746