Computing Euclidean distance for numpy in python

前端 未结 3 1685
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 01:03

I am new to Python so this question might look trivia. However, I did not find a similar case to mine. I have a matrix of coordinates for 20 nodes. I want to compute the euc

3条回答
  •  萌比男神i
    2020-12-09 01:29

    What I figure you wanted to do: You said you wanted a 20 by 20 matrix... but the one you coded is triangular.

    Thus I coded a complete 20x20 matrix instead.

    distances = []
    for i in range(len(ncoord)):
        given_i = []
        for j in range(len(ncoord)):
            d_val = math.sqrt((ncoord[i, 0]-ncoord[j,0])**2+(ncoord[i,1]-ncoord[j,1])**2)
            given_i.append(d_val)
    
        distances.append(given_i)
    
        # distances[i][j] = distance from i to j
    

    SciPy way:

    from scipy.spatial.distance import cdist
    # Isn't scipy nice - can also use pdist... works in the same way but different recall method.
    distances = cdist(ncoord, ncoord, 'euclidean')
    

提交回复
热议问题