【问题标题】:Sort matrix based on the nearest distance between two coordinates根据两个坐标之间的最近距离对矩阵进行排序
【发布时间】:2018-06-16 23:24:34
【问题描述】:

如何根据两个坐标之间的最近距离对矩阵进行排序?

例如,我有这个矩阵:

> 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,])
  }

【问题讨论】:

  • 如果例如 x 改为 matrix(c(1,1,2,2,1,2,6,8),ncol=2),结果会在第 1 行和第 2 行之间来回切换,或者我们会将最接近第 2 行但不是第 1 行的对放入第 3 行?
  • 我觉得你应该看看travelling salesman problem

标签: r matrix distance


【解决方案1】:

这是一个使用循环的可能解决方案:

## We determine the minimum distance between the coordinates at the current index cur 
## and those at the remaining indexes ind
cur = 1;    
ind = c(2:nrow(x));
## We put our resulting sorted indexes in sorted
sorted = 1;
while(length(ind)>=2){
    pos = ind[which.min(rowSums((x[cur,]-x[ind,])^2))];
    ## At each iteration we remove the newly identified pos from the indexes in ind
    ## and consider it as the new current position to look at
    ind = setdiff(ind,pos);
    cur = pos;
    sorted = c(sorted,pos)}
sorted = c(sorted,ind)

res = x[sorted,];

     [,1] [,2]
[1,]    1    1
[2,]    2    6
[3,]    2    8
[4,]    3    9

【讨论】:

    【解决方案2】:

    您可以使用如下所示的 for 循环:

    D=`diag<-`(as.matrix(dist(x)),NA)# Create the distance matrix, and give the diagonals NA values.
    

    然后运行一个for循环

    x[c(i<-1,sapply(1:(nrow(x)-1),function(j)i<<-which.min(D[i,]))),]
    
         [,1] [,2]
    [1,]    1    1
    [2,]    2    6
    [3,]    2    8
    [4,]    3    9
    

    这个 for 循环可能看起来很奇怪!看看:

    m=c()
    i=1
    for(j in 1:(nrow(x)-1)){
    i= which.min(D[i,])
    m=c(m,i)
    }
    x[c(1,m),]
         [,1] [,2]
    [1,]    1    1
    [2,]    2    6
    [3,]    2    8
    [4,]    3    9
    

    你也可以使用Reduce

    x[Reduce(function(i,j)which.min(D[,i]),1:(nrow(x)-1),1,,T),]
         [,1] [,2]
    [1,]    1    1
    [2,]    2    6
    [3,]    2    8
    [4,]    3    9
    

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 2016-10-31
      • 2022-06-16
      • 2021-01-01
      • 2017-10-11
      • 2017-06-21
      • 2022-11-21
      • 2012-08-06
      • 1970-01-01
      相关资源
      最近更新 更多