St123
St123

Reputation: 320

Apply hstack on an array of matrices

Given an array of matrices matrices_w I want to apply the np.hstack function on each matrix:

matrices_w = np.asarray([[[1,2,3],[4,5,6]],[[9,8,7],[6,5,4]]])
array([[[1, 2, 3],
        [4, 5, 6]],

       [[9, 8, 7],
        [6, 5, 4]]])

such that the desired result is given by:

array([[1, 2, 3, 4, 5, 6],
       [9, 8, 7, 6, 5, 4]])

So far I have tried several functions including np.apply_along_axis but could not get things to work.

Upvotes: 2

Views: 498

Answers (1)

hpaulj
hpaulj

Reputation: 231385

In this case reshape is easiest and fastest way. But it may be worth while figuring out why hstack does not work.

In [192]: arr = np.array([[[1,2,3],[4,5,6]],[[9,8,7],[6,5,4]]])              

hstack runs, but produces a different order:

In [193]: np.hstack(arr)                                                     
Out[193]: 
array([[1, 2, 3, 9, 8, 7],
       [4, 5, 6, 6, 5, 4]])

that's because hstack treats the first dimension of the array as a list, and joins the two arrays:

In [194]: np.concatenate([arr[0],arr[1]], axis=-1)                           
Out[194]: 
array([[1, 2, 3, 9, 8, 7],
       [4, 5, 6, 6, 5, 4]])

If we split it into lists on the 2nd dimension we get the order you want:

In [195]: np.concatenate([arr[:,0],arr[:,1]], axis=-1)                       
Out[195]: 
array([[1, 2, 3, 4, 5, 6],
       [9, 8, 7, 6, 5, 4]])

Upvotes: 3

Related Questions