pythonnumpylinear-algebra

"Cloning" row or column vectors


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?


Solution

  • 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])
    >>> x
    array([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]])