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

Robert Kern robert.kern@gmail....
Tue Feb 8 10:46:34 CST 2011


On Tue, Feb 8, 2011 at 10:44, Ben Gamari <bgamari.foss@gmail.com> wrote:
> I have an array of (say, row) vectors,
>
>  v = [ [ a1, a2, a3 ],
>        [ b1, b2, b3 ],
>        [ c1, c2, c3 ],
>        ...
>      ]
>
> What is the optimal way to compute the norm of each vector,
>  norm(v)**2 = [
>      [ a1**2 + a2**2 + a3**2 ],
>      [ b1**2 + b2**2 + b3**2 ],
>      ...
>    ]
>
> It seems clear that numpy.norm does not handle the multidimensional case
> as needed. The best thing I can think of is to do something like,
>
>  sum(v**2, axis=0) * ones(3)
>
> but surely there must be a better way. Any ideas?

(v*v).sum(axis=1)[:,np.newaxis]

You can leave off the newaxis bit if you don't really need a column vector.

-- 
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