simple array multiplication question
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 N1: 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.
On 12Oct09, at 11:53 PM, per freem wrote:
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]
This isn't picking columns of p, this is picking the times at (0, 0), (1, 0), and (2, 1). Is this what you meant? In [36]: p[arange(3), [0,0,1]] Out[36]: array([ 0.2, 0.5, 0.7]) In [37]: p[:, [0,0,1]] Out[37]: array([[ 0.2, 0.2, 0.8], [ 0.5, 0.5, 0.5], [ 0.3, 0.3, 0.7]]) In [38]: p[arange(3), [0,0,1]] * s.reshape(3,1) Out[38]: array([[ 2., 5., 7.], [ 4., 10., 14.], [ 6., 15., 21.]]) In [41]: p[:, [0,0,1]] * s.reshape(3,1) Out[41]: array([[ 2., 2., 8.], [ 10., 10., 10.], [ 9., 9., 21.]]) Notice the difference.
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?
That's about as efficient as it gets, I think.
also, is the reshape operation expensive?
No. It will return a view, rather than make a copy. You could also do cols * s[:, np.newaxis], equivalently. David
participants (2)

David WardeFarley

per freem