'Manhattan distance between 2 vectors
I need to calculate the manhattan distance between 2 vectors
I found this code https://www.geeksforgeeks.org/sum-manhattan-distances-pairs-points/
def distancesum (x, y, n):
sum = 0
# for each point, finding distance
# to rest of the point
for i in range(n):
for j in range(i+1,n):
sum += (abs(x[i] - x[j]) +
abs(y[i] - y[j]))
return sum
But in another documentation I found this code for manhattan
so the code for this is:
def manhattan_distance(instance1, instance2):
n = len(instance1)-1
sum = 0
# for each point, finding distance
# to rest of the point
for i in range(n):
sum += abs(float(instance1[i]) - float(instance2[i]))
return sum
What is the algorithm for manhattan distance
Solution 1:[1]
Here's an example for calculating the manhattan distance.
In [1]: %paste
import numpy as np
def manhattan_distance(a, b):
return np.abs(a - b).sum()
a = np.array([1, 2])
b = np.array([-1, 4])
print(manhattan_distance(a, b))
## -- End pasted text --
4
If dealing with vectors that are strings
In [1]: %paste
import numpy as np
def manhattan_distance(a, b):
return np.abs(a - b).sum()
a = ['1', '2']
b = ['-1', '4']
print(manhattan_distance(np.array(a, dtype=float), np.array(b, dtype=float)))
## -- End pasted text --
4.0
Solution 2:[2]
In the referenced formula, you have n points each with 2 coordinates and you compute the distance of one vectors to the others. So apart from the notations, both formula are the same. The Manhattan distance between 2 vectors is the sum of the absolute value of the difference of their coordinates. An easy way to remember it, is that the distance of a vector to itself must be 0.
Solution 3:[3]
You probably need this Scipy function:
Y = cdist(XA, XB, 'cityblock')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Serge Ballesta |
Solution 3 |