R语言 如何计算欧几里得距离
欧氏空间中两点之间的欧氏距离是两点之间线段的长度。它可以用毕达哥拉斯定理从两点的笛卡尔坐标计算出来,因此偶尔也被称为毕达哥拉斯距离。两个向量之间的欧氏距离由以下公式给出
√Σ(vect1i - vect2i)2
其中。
- vect1是第一个矢量
- vect2是第二个向量
例如,我们有两个向量,vect1为(1,4,3,5),vect2为(2,3,2,4)。它们的欧氏距离为:√(1-2)2 +(4-3)2 +(3-2)2 +(5-4)2 ,等于2。
例1 :
# Function to calculate Euclidean distance
# Sum function calculates the sum of the
# squares of absolute difference between
# corresponding elements of vect1 and vect2
CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2))
# Initializing two vectors having equal length
vect1 <- c(2, 4, 4, 7)
vect2 <- c(1, 2, 2, 10)
print("Euclidean distance between vect1 and vect2 is: ")
# Calling CalculateEuclideanDistance function
CalculateEuclideanDistance(vect1, vect2)
输出 。
例2 :
# Function to calculate Euclidean distance
# Sum function calculates the sum of the
# squares of absolute difference between
# corresponding elements of vect1 and vect2
CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2))
# Initializing two vectors having equal length
vect1 <- c(2, 3, 4, 7)
vect2 <- c(1, 2, 3, 8)
print("Euclidean distance between vect1 and vect2 is: ")
# Calling CalculateEuclideanDistance function
CalculateEuclideanDistance(vect1, vect2)
输出 。
如果两个向量的长度不相等,编译器会给出一个警告信息。下面是使用两个不等长的向量的实现。
例3 :
# Function to calculate Euclidean distance
# Sum function calculates the sum of the
# squares of absolute difference between
# corresponding elements of vect1 and vect2
CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2))
# Initializing two vectors having equal length
vect1 <- c(4, 3, 4, 8)
vect2 <- c(3, 2, 3, 1, 2)
print("Euclidean distance between vect1 and vect2 is: ")
# Calling CalculateEuclideanDistance function
CalculateEuclideanDistance(vect1, vect2)
输出 。
正如你在输出中看到的,由于vect1的长度比vect2短,编译器给了我们一个警告。
例4 :
# Function to calculate Euclidean distance
# Sum function calculates the sum of the
# squares of absolute difference between
# corresponding elements of vect1 and vect2
CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2))
# Initializing two vectors having equal length
vect1 <- c(1, 7, 1, 3, 10, 15 )
vect2 <- c(3, 2, 10, 11 )
print("Euclidean distance between vect1 and vect2 is: ")
# Calling CalculateEuclideanDistance function
CalculateEuclideanDistance(vect1, vect2)
输出 。
正如你在输出中看到的,编译器给了我们一个警告,因为vect2的长度比vect1短。