[Numpy-discussion] Computing the norm of an array of vectors

Ben Gamari bgamari.foss at gmail.com
Tue Feb 8 13:19:57 EST 2011


On Tue, 08 Feb 2011 18:06:48 +0000, Andrew Jaffe <a.h.jaffe at gmail.com> wrote:
> For this shape=(N,3) vector, this is not what you mean: as Robert Kern 
> also has it you want axis=1, which produces a shape=(N,) (or the 
> [:,newaxis] version which produces shape=(N,1).
> 
> But what is the point of the ones(3)? I think you intend to make a new 
> (N,3) array where each row duplicates the norm, so that you can then 
> divide out the norms. But through the magic of broadcasting, that's not 
> necessary:
> 
> v/np.sqrt(sum(v**2, axis=1)[:,newaxis])
> 
> does what you want.
> 
Thanks! I've since realized the error in my ways. I had completely
forgotten that newaxis existed. Robert Kern's proposal is perfect.

- Ben



More information about the NumPy-Discussion mailing list