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

Ken Basye kbasye1 at jhu.edu
Tue Feb 17 10:30:56 EST 2009


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. 

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.

Thanks,
     Ken




More information about the NumPy-Discussion mailing list