[Numpy-discussion] Norm of array of vectors

gary ruben gruben at bigpond.net.au
Thu Mar 17 05:58:18 EDT 2011


How about

argmin(add.reduce((a*a),axis=1))


In [5]: a
Out[5]:
array([[ 0.24202827,  0.01269182,  0.95162307],
       [ 0.02979253,  0.4333354 ,  0.49650111],
       [ 0.52626565,  0.08363861,  0.56444878],
       [ 0.89639659,  0.54259354,  0.29245881],
       [ 0.75301013,  0.6248646 ,  0.24565827],
       [ 0.67501358,  0.58920861,  0.37420961],
       [ 0.8776001 ,  0.58055258,  0.16623637],
       [ 0.26271551,  0.24441225,  0.47543652],
       [ 0.12793549,  0.88453877,  0.8479841 ],
       [ 0.49148293,  0.45352964,  0.65575962]])

In [6]: argmin(add.reduce((a*a),axis=1))
Out[6]: 7

In [7]: timeit argmin(array([sqrt(dot(x,x)) for x in a]))
10000 loops, best of 3: 67.2 us per loop

In [8]: timeit argmin(array([dot(x,x) for x in a]))
10000 loops, best of 3: 36 us per loop

In [9]: timeit argmin(add.reduce((a*a),axis=1))
100000 loops, best of 3: 13.6 us per loop

Gary R

On Thu, Mar 17, 2011 at 7:44 PM, Andrey N. Sobolev <inconnu at list.ru> wrote:
> Dear all,
>
> Sorry if that's a noob question, but anyway. I have several thousands of
> vectors stacked in 2d array. I'd like to get new array containing
> Euclidean norms of these vectors and get the vector with minimal norm.
>
> Is there more efficient way to do this than
> argmin(array([sqrt(dot(x,x)) for x in vec_array]))?
>
> Thanks in advance.
> Andrey.



More information about the NumPy-Discussion mailing list