簡體   English   中英

根據兩個坐標之間的最近距離對矩陣進行排序

[英]Sort matrix based on the nearest distance between two coordinates

如何根據兩個坐標之間的最近距離對矩陣進行排序?

例如,我有這個矩陣:

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

這是使用循環的可能解決方案:

## 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

您可以使用如下所示的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM