[Numpy-discussion] Computing the norm of an array of vectors
Andrew Jaffe
a.h.jaffe at gmail.com
Tue Feb 8 13:06:48 EST 2011
On 08/02/2011 16:44, Ben Gamari 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)
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.
Andrew
More information about the NumPy-Discussion
mailing list