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

Charles R Harris charlesr.harris@gmail....
Tue Feb 17 12:04:56 CST 2009

```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/20090217/6880612b/attachment.html
```