如何编写一个for循环来创建50个不同点之间的欧几里德距离矩阵?R

如何编写一个for循环来创建50个不同点之间的欧几里德距离矩阵?R,r,for-loop,matrix,adjacency-matrix,R,For Loop,Matrix,Adjacency Matrix,我已经创建了一个由50个随机生成的(x,y)对组成的矩阵,我需要将其转换为一个矩阵,显示从任何点(行中)到所有其他点(列中)的距离。这将导致对角线0,并且是一个50 x 50的矩阵 我将使用以下公式计算距离: 创建距离矩阵: n = 50 x = round(runif(n)*1000) y = round(runif(n)*1000) coordinates = cbind(x,y) head(coordinates) x y [1,] 266 478 [2,] 372

我已经创建了一个由50个随机生成的(x,y)对组成的矩阵,我需要将其转换为一个矩阵,显示从任何点(行中)到所有其他点(列中)的距离。这将导致对角线0,并且是一个50 x 50的矩阵

我将使用以下公式计算距离:

创建距离矩阵:

n = 50
x = round(runif(n)*1000)
y = round(runif(n)*1000)
coordinates = cbind(x,y)

head(coordinates)
       x   y
[1,] 266 478
[2,] 372 861
[3,] 573 438
[4,] 908 245
[5,] 202  71
[6,] 898  99
我尝试了以下方法,但正如您从
length(distance)
输出中看到的,distance中的元素数并不像我预期的那样为2500。此外,距离的第一个元素是445.4863,而不是我希望的0

distances = c()
for (i in 1:n)
  for (j in 1:n)
    distances[i] = sqrt((coordinates[j,2]-coordinates[i,2])^2 + (coordinates[j,1]-coordinates[i,1])^2)

length(distances)     #This should be 2500 elements long
[1] 50           

distances = matrix(distances, nrow=n, ncol=n)       


原始代码的问题在于,您将每次迭代时计算的距离保存到距离[i]。这意味着对于
i
的每个值,您将覆盖
j
的每个值的相同位置。您可以通过计算一个同时考虑
i
j
的索引来解决这个问题:

distances = c()
for (i in 1:n) {
    for (j in 1:n) {
        distances[(i - 1) * n + j] = sqrt((coordinates[j,2]-coordinates[i,2])^2 +
                                          (coordinates[j,1]-coordinates[i,1])^2)
    }
}

但是,我不推荐这种方法,因为当有矢量化方法可用时,R中的循环非常慢。至少,您应该使用类似于
distance=numeric(n*n)
的方法预先分配距离向量,因为在R中多次调整向量的大小特别慢。

as.matrix(dist(coordinates))
这可以完美地工作。我不知道
dist()
函数