"Cloning" row or column vectors "Cloning" row or column vectors python python

"Cloning" row or column vectors


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]])


Here's an elegant, Pythonic way to do it:

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

the problem with [16] seems to be that the transpose has no effect for an array. you're probably wanting a matrix instead:

>>> x = array([1,2,3])>>> xarray([1, 2, 3])>>> x.transpose()array([1, 2, 3])>>> matrix([1,2,3])matrix([[1, 2, 3]])>>> matrix([1,2,3]).transpose()matrix([[1],        [2],        [3]])


First note that with numpy's broadcasting operations it's usually not necessary to duplicate rows and columns. See this and this for descriptions.

But to do this, repeat and newaxis are probably the best way

In [12]: x = array([1,2,3])In [13]: repeat(x[:,newaxis], 3, 1)Out[13]: array([[1, 1, 1],       [2, 2, 2],       [3, 3, 3]])In [14]: repeat(x[newaxis,:], 3, 0)Out[14]: array([[1, 2, 3],       [1, 2, 3],       [1, 2, 3]])

This example is for a row vector, but applying this to a column vector is hopefully obvious. repeat seems to spell this well, but you can also do it via multiplication as in your example

In [15]: x = array([[1, 2, 3]])  # note the double bracketsIn [16]: (ones((3,1))*x).transpose()Out[16]: array([[ 1.,  1.,  1.],       [ 2.,  2.,  2.],       [ 3.,  3.,  3.]])