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

Ken Basye kbasye1@jhu....
Tue Feb 17 09:30:56 CST 2009

   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. 

Note that the expression np.outer(m, m) will always produce an array 
with shape (p, p) where p is the product over the shape of m.  E.g. if 
m.shape == (10, 4) then outer(m, m).shape == (40, 40) whereas I want 
something with shape (10, 4, 4).   I suppose all the values I want are 
indeed somewhere in this 2d array, since it contains every pairwise 
product, but I'm not sure I want to do that much extra computation just 
to avoid the loop, plus I'd still have to figure out how to get a view 
that covered only the results I care about.


More information about the Numpy-discussion mailing list