如何根据两个坐标之间的最近距离对矩阵进行排序?
例如,我有这个矩阵:
> x
[,1] [,2]
[1,] 1 1
[2,] 3 9
[3,] 2 6
[4,] 2 8
我希望矩阵的第一行可以作为一个初始坐标。在手动计算两个坐标之间的距离后,我发现x [1,]
与x [3,]
之间的距离最近。然后,x [3,]
与x [4,]
之间的距离最近。x [4,]
与x [2,]
之间的距离最近。因此,排序后的矩阵如下:
[,1] [,2]
[1,] 1 1
[2,] 2 6
[3,] 2 8
[4,] 3 9
我尝试编写以下的 R 代码,但它没有起作用。
closest.pair <- c(NA,NA)
closest.distance <- Inf
for (i in 1:(n-1))
for (j in (i+1):n) {
dist <- sum((houses[i,]-houses[j,])^2)
if (dist<closest.distance) {
closest.pair <- c(i,j)
}
print(houses[closest.pair,])
}
matrix(c(1,1,2,2,1,2,6,8),ncol=2)
,结果会在第一行和第二行之间来回移动,还是我们把最接近第二行但不是第一行的一对放在第三行? - Lamia