----------------------------------------------------------------------
Message: 1
Date: Tue, 17 Feb 2009 11:04:56 -0700
From: Charles R Harris <[email protected]>
Subject: Re: [Numpy-discussion] Compute multiple outer products
without a loop?
To: Discussion of Numerical Python <[email protected]>
Message-ID:
<[email protected]>
Content-Type: text/plain; charset="iso-8859-1"
On Tue, Feb 17, 2009 at 8:30 AM, Ken Basye <[email protected]> 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