[Numpy-discussion] "Extended" Outer Product
Robert Kern
robert.kern@gmail....
Mon Aug 20 17:37:01 CDT 2007
Geoffrey Zhu wrote:
> Hi Everyone,
>
> I am wondering if there is an "extended" outer product. Take the
> example in "Guide to Numpy." Instead of doing an multiplication, I
> want to call a custom function for each pair.
>
>>>> print outer([1,2,3],[10,100,1000])
>
> [[ 10 100 1000]
> [ 20 200 2000]
> [ 30 300 3000]]
>
>
> So I want:
>
> [
> [f(1,10), f(1,100), f(1,1000)],
> [f(2,10), f(2, 100), f(2, 1000)],
> [f(3,10), f(3, 100), f(3,1000)]
> ]
>
> Does anyone know how to do this without using a double loop?
If you can code your function such that it only uses operations that broadcast
(i.e. operators and ufuncs) and avoids things like branching or loops, then you
can just use numpy.newaxis on the first array.
from numpy import array, newaxis
x = array([1, 2, 3])
y = array([10, 100, 1000])
f(x[:,newaxis], y)
Otherwise, you can use numpy.vectorize() to turn your function into one that
will do that broadcasting for you.
from numpy import array, newaxis, vectorize
x = array([1, 2, 3])
y = array([10, 100, 1000])
f = vectorize(f)
f(x[:,newaxis], y)
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Numpy-discussion
mailing list