简体   繁体   中英

How do I iterate over an ndarray without using for/while loops?

For two given 1-d arrays or lists I can calculate the squared Euclidean distance via the function

import numpy as np

def npdistance(x1, x2):

    return sum((np.array(x1)-np.array(x2))**2)

Now for a given vector v and 2d-array XI would like to find the shortest squared Euclidean distance of any vector contained in X to the vector u without iterating over the elements of X with for/while loops. My attempt is

def npnearest(u, X):
    L=npdistance(u,X)
    return min(L)

which does not give me what I want. For example

 npnearest(np.array([1,1,1]), np.array([[1,1,1],[2,3,4]]))

would give me 16 instead of 0. How can I do it?

In case of numpy, prefer np.sum and np.min , rather than Python buildins sum and min .

We can adapt npdistance for 2D numpy vectors:

def npdistance(x1, x2):
    return np.sum((np.array(x1)-np.array(x2))**2, axis=1)

Consider matrix x2 :

x2 = np.array([[1,1,1],[2,3,4]])

Matrix x2 has two axes:

  • zeroth is vector number: x2[0] is np.array([1, 1, 1]) and x2[1] is np.array([2, 3, 4]) ,
  • first axis is for vector dimension: x2[1][1] is 3 (second element of first vector).

We perform sum along axis=1 to get distances for each vector.

  • Without np.sum axis=1 it would return scalar,
  • Using buildin sum gives sum of all vectors (ala axis=0 ).

npnearest works correct in this case.

def npnearest(u, X):
    L=npdistance(u,X)
    return min(L)

npnearest(np.array([1,1,1]), np.array([[1,1,1],[2,3,4]]))

gives 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM