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

Ken Basye kbasye1@jhu....
Wed Feb 18 09:40:44 CST 2009


Thanks Chuck; that's perfect.
   Ken
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Tue, 17 Feb 2009 11:04:56 -0700
> From: Charles R Harris <charlesr.harris@gmail.com>
> Subject: Re: [Numpy-discussion] Compute multiple outer products
> 	without a	loop?
> To: Discussion of Numerical Python <numpy-discussion@scipy.org>
> Message-ID:
> 	<e06186140902171004g850c9aax348a3e2053bb69fa@mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> On Tue, Feb 17, 2009 at 8:30 AM, Ken Basye <kbasye1@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://projects.scipy.org/pipermail/numpy-discussion/attachments/20090218/38ea5d4f/attachment-0001.html 


More information about the Numpy-discussion mailing list