[Numpy-discussion] Multiply along axis

Skipper Seabold jsseabold at gmail.com
Wed Jun 29 10:38:38 EDT 2011


On Wed, Jun 29, 2011 at 10:32 AM, Robert Elsner <mlist at re-factory.de> wrote:
>
> Hello everyone,
>
> I would like to solve the following problem (preferably without
> reshaping / flipping the array a).
>
> Assume I have a vector v of length x and an n-dimensional array a where
> one dimension has length x as well. Now I would like to multiply the
> vector v along a given axis of a.
>
> Some example code
>
> a = np.random.random((2,3))
> x = np.zeros(2)
>
> a * x   # Fails because not broadcastable
>
>
> So how do I multiply x with the columns of a so that for each column j
> a[:,j] = a[:,j] * x
>
> without using a loop. Is there some (fast) fast way to accomplish that
> with numpy/scipy?
>

Is this what you want?

a * x[:,None]

or

a *  x[:,np.newaxis]

or more generally

a * np.expand_dims(x,1)

Skipper



More information about the NumPy-Discussion mailing list