[Numpy-discussion] Multiply along axis
josef.pktd@gmai...
josef.pktd@gmai...
Wed Jun 29 18:57:59 CDT 2011
On Wed, Jun 29, 2011 at 11:05 AM, Robert Elsner <mlist@re-factory.de> wrote:
>
> Yeah great that was spot-on. And I thought I knew most of the slicing
> tricks. I combined it with a slice object so that
>
> idx_obj = [ None for i in xrange(a.ndim) ]
or
idx_obj = [None] * a.ndim
otherwise this is also what I do quite often
Josef
> idx_obj[axis] = slice(None)
>
> a * x[idx_object]
>
> works the way I want it. Suggestions are welcome but I am happy with the
> quick solution you pointed out. Thanks
>
>
> On 29.06.2011 16:38, Skipper Seabold wrote:
>> On Wed, Jun 29, 2011 at 10:32 AM, Robert Elsner <mlist@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
>> _______________________________________________
>> NumPy-Discussion mailing list
>> NumPy-Discussion@scipy.org
>> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
More information about the NumPy-Discussion
mailing list