[Numpy-discussion] simple array multiplication question

per freem perfreem@gmail....
Mon Oct 12 22:53:05 CDT 2009


hi all,

i am trying to write a simple product of 3 arrays (as vectorized code)
but am having some difficulty. i have three arrays, one is a list
containing several lists:

p = array([[ 0.2,  0.8], [ 0.5,  0.5], [ 0.3,  0.7]])

each list in the array 'p' is of size N -- in this case N = 2. i have
a second array containing a set of numbers, each between 0 and N-1:

l = array([0, 0, 1])

and finally an array of the same size as l:

s = array([10, 20, 30])

what i want to do is pick the columns l of p, and multiply each one by
the numbers in s. the first step, picking columns l of p, is simply:

cols = p[arange(3), l]

then i want to multiply each one by the numbers in s, and i do it like this:

cols * s.reshape(3,1)

this seems to work, but i am concerned that it might be inefficient.
is there a cleaner way of doing this? is 'arange' operation necessary
to reference all the 'l' columns of p? also, is the reshape operation
expensive?

thanks very much.


More information about the NumPy-Discussion mailing list