[Numpy-discussion] Compute multiple outer products, without a loop?

Ken Basye kbasye1 at jhu.edu
Wed Feb 18 10:40:44 EST 2009


Thanks Chuck; that's perfect.
   Ken
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Tue, 17 Feb 2009 11:04:56 -0700
> From: Charles R Harris <charlesr.harris at gmail.com>
> Subject: Re: [Numpy-discussion] Compute multiple outer products
> 	without a	loop?
> To: Discussion of Numerical Python <numpy-discussion at scipy.org>
> Message-ID:
> 	<e06186140902171004g850c9aax348a3e2053bb69fa at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> On Tue, Feb 17, 2009 at 8:30 AM, Ken Basye <kbasye1 at jhu.edu> wrote:
>
>   
>> Hi,
>>   My current code looks like this:
>>
>>           (k,d) = m.shape
>>           sq = np.zeros((k, d, d), dtype=float)
>>           for i in xrange(k):
>>               sq[i] = np.outer(m[i], m[i])
>>
>>
>> That is, m is treated as a sequence of k vectors of length d; the k dXd
>> outer products are found and stored in sq.
>>
>>     
>
> Try A[:,:,newaxis]*B[:,newaxis,:] . Example
>
> In [6]: A = array([[1,2],[3,4]])
>
> In [7]: B = array([[1,1],[1,1]])
>
> In [8]: A[:,:,newaxis]*B[:,newaxis,:]
> Out[8]:
> array([[[1, 1],
>         [2, 2]],
>
>        [[3, 3],
>         [4, 4]]])
>
> In [9]: B[:,:,newaxis]*A[:,newaxis,:]
> Out[9]:
> array([[[1, 2],
>         [1, 2]],
>
>        [[3, 4],
>         [3, 4]]])
>
> You can use this sort of trick along with a sum to multiply stacks of
> matrices by stacks of vectors or matrices.
>
> Chuck
>
>   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20090218/38ea5d4f/attachment.html>


More information about the NumPy-Discussion mailing list