[Numpy-discussion] Tuple outer product?
Alan G Isaac
aisaac@american....
Fri Sep 25 18:46:22 CDT 2009
OK, sure, for large arrays meshgrid will look bad.
(It creates a large array twice.) If the example
really involves sequential integers, then mgrid
could be used instead to save on this.
Even so, it is just implausible that duplicating
meshgrid functionality will be faster than using meshgrid.
So let's avoid the transpose of a big matrix by
using dstack, and voila, it's competitive again.
But with large arrays, itertools.product will look *even* better.
It is by far the fastest, and of course even faster
yet if you do not convert to list (since it returns
a generator). Not to mention, it returns the pairs
(in contrast to the nesting in the other solutions).
Alan
#script
from numpy import arange, array, dstack, empty, meshgrid, repeat
from itertools import product
import timeit
def mesh1(a, b):
(n,m) = (a.shape[0],b.shape[0])
a = repeat(a,m).reshape(n,m)
b = repeat(b,n).reshape(m,n).transpose()
ab = dstack((a,b))
return ab.tolist()
def mesh2(a, b):
return array(meshgrid(a,b)).transpose().tolist()
def mesh3(a, b):
ab = empty((a.shape[0], b.shape[0], 2), dtype=int)
ab.T[0] = a
ab[:,:,1] = b
return ab.tolist()
def mesh4(a, b):
return dstack(meshgrid(a,b)).tolist()
def mesh5(a,b):
return list(product(a,b))
a = arange(1000)
b = arange(1000)
print
for f in mesh1, mesh2, mesh3, mesh4, mesh5:
print timeit.timeit('f(a,b)',setup='from __main__ import a,b,f', number=10)
#results
12.3801448229
16.1959892249
11.7581712899
12.3436149706
1.24762749176
More information about the NumPy-Discussion
mailing list