"Cloning" row or column vectors

Boris Gorelik picture Boris Gorelik · Oct 11, 2009 · Viewed 131.9k times · Source

Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as

[1,2,3]

Into a matrix

[[1,2,3]
 [1,2,3]
 [1,2,3]
]

or a column vector such as

[1
 2
 3
]

into

[[1,1,1]
 [2,2,2]
 [3,3,3]
]

In matlab or octave this is done pretty easily:

 x = [1,2,3]
 a = ones(3,1) * x
 a =

    1   2   3
    1   2   3
    1   2   3

 b = (x') * ones(1,3)
 b =

    1   1   1
    2   2   2
    3   3   3

I want to repeat this in numpy, but unsuccessfully

In [14]: x = array([1,2,3])
In [14]: ones((3,1)) * x
Out[14]:
array([[ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.]])
# so far so good
In [16]: x.transpose() * ones((1,3))
Out[16]: array([[ 1.,  2.,  3.]])
# DAMN
# I end up with 
In [17]: (ones((3,1)) * x).transpose()
Out[17]:
array([[ 1.,  1.,  1.],
       [ 2.,  2.,  2.],
       [ 3.,  3.,  3.]])

Why wasn't the first method (In [16]) working? Is there a way to achieve this task in python in a more elegant way?

Answer

pv. picture pv. · Oct 17, 2009

Use numpy.tile:

>>> tile(array([1,2,3]), (3, 1))
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

or for repeating columns:

>>> tile(array([[1,2,3]]).transpose(), (1, 3))
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])