Oscar Muñoz
Oscar Muñoz

Reputation: 439

Vectorized way to arrange vector into matrix (numpy)

I have 4 vectors of the same dimentions (say 3)

a= [1, 5, 9]
b= [2, 6, 10]
c= [3, 7, 11]
d= [4, 8, 12]

What i want to do with numpy is to create a matrix of dimensions 3x2x2 that has this structure

enter image description here

so the resultan matrices will be like this

[
[[1, 2],[3,4]],
[[5, 6],[7,8]],
[[9, 10],[11,12]],
]

I know that it is pretty easy using a for loop but I'm looking for a vectorized approach.

Thanks in advance

Upvotes: 0

Views: 1138

Answers (2)

muskrat
muskrat

Reputation: 1559

np.reshape() will do it:

np.reshape(np.array([a,b,c,d]).T,[3,2,2])

will produce the desired result.

Upvotes: 1

hpaulj
hpaulj

Reputation: 231385

np.stack is handy tool for combining arrays (or in this case lists) in various orders:

In [74]: a= [1, 5, 9]
    ...: b= [2, 6, 10]
    ...: c= [3, 7, 11]
    ...: d= [4, 8, 12]
    ...: 
    ...:

Default without axis parameter is like np.array, adding a new initial dimension:

In [75]: np.stack((a,b,c,d))
Out[75]: 
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

But the order isn't what you want. Lets try axis=1:

In [76]: np.stack((a,b,c,d),1)
Out[76]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

Order looks right. Now add a reshape:

In [77]: np.stack((a,b,c,d),1).reshape(3,2,2)
Out[77]: 
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],

       [[ 9, 10],
        [11, 12]]])

Another approach is to join the lists, reshape and transpose:

In [78]: np.array([a,b,c,d])
Out[78]: 
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])
In [79]: _.reshape(2,2,3)
Out[79]: 
array([[[ 1,  5,  9],
        [ 2,  6, 10]],

       [[ 3,  7, 11],
        [ 4,  8, 12]]])
In [80]: _.transpose(2,1,0)
Out[80]: 
array([[[ 1,  3],
        [ 2,  4]],

       [[ 5,  7],
        [ 6,  8]],

       [[ 9, 11],
        [10, 12]]])
In [81]: __.transpose(2,0,1)
Out[81]: 
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],

       [[ 9, 10],
        [11, 12]]])

We can try to be systematic about this, but I find it instructive to experiment, trying various alternatives.

Upvotes: 2

Related Questions