[Numpy-discussion] "Extended" Outer Product

Christopher Barker Chris.Barker at noaa.gov
Mon Aug 20 19:51:55 EDT 2007


Robert Kern wrote:
> 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)

in fact, it may make sense to just have your x be column vector anyway:
 >>> x
array([1, 2, 3])
 >>> y
array([10, 11, 12])
 >>> x.shape = (-1,1)
 >>> x
array([[1],
        [2],
        [3]])
 >>> x * y
array([[10, 11, 12],
        [20, 22, 24],
        [30, 33, 36]])

Broadcasting is VERY cool!

-Chris


-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov



More information about the NumPy-Discussion mailing list