[Numpy-discussion] Howto vectorise a dot product ?

David Warde-Farley dwf at cs.toronto.edu
Tue Jun 9 16:27:51 EDT 2009

On 9-Jun-09, at 2:56 PM, bruno Piguet wrote:
> Phi is now of size(n) and V (n, 3).
> (I really whish to have this shape, for direct correspondance to  
> file).
> The corresponding function looks like :
> def rotat_vect(phi, V):
>    s = np.sin(phi)
>    c = np.cos(phi)
>    M = np.zeros((len(phi), 3, 3))
>    M[:, 2, 2] = M[:, 1, 1] = c
>    M[:, 1, 2] = -s
>    M[:, 2, 1] = s
>    M[:, 0, 0] = np.ones (len(phi))
>    return np.dot(M, V)

Well, if you make V have a singleton dimension on the end you can then  
do it, but you will get one more axis than you care about.

The help for dot() says this:

     For 2-D arrays it is equivalent to matrix multiplication, and for  
     arrays to inner product of vectors (without complex conjugation).  
     N dimensions it is a sum product over the last axis of `a` and
     the second-to-last of `b`::

         dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

So changing your code to this:
	return np.dot(M, V[:,:,np.newaxis])[arange(len(phi)), :,  
arange(len(phi)), :]

will do what you want, but it will also do a lot of useless  
multiplication in computing that product. I'm not sure of any better  
way, and am kind of curious myself (since I often have to take  
products of one or several vectors with several matrices).


More information about the NumPy-Discussion mailing list