Search code examples
pythonnumpyarray-broadcasting

How to broadcast an array by columns?


I want to add every columns of a matrix to a numpy array, but numpy.broadcast only allows to add every rows of a matrix to an array. How can I do this?

My idea is to first transpose the matrix then add it to the array then transpose back, but this uses two transposes. Is there a function to do it directly?


Solution

  • Instead of using an array you could use a second matrix with just one column:

    matrix = np.matrix(np.zeros((3,3)))
    array = np.matrix([[1],[2],[3]])
    matrix([[1],
            [2],
            [3]])
    matrix + array
    matrix([[ 1.,  1.,  1.],
            [ 2.,  2.,  2.],
            [ 3.,  3.,  3.]])
    

    If you originally have an array you can reshape it like this:

    a = np.asarray([1,2,3])
    matrix + np.reshape(a, (3,1))
    matrix([[ 1.,  1.,  1.],
            [ 2.,  2.,  2.],
            [ 3.,  3.,  3.]])