简体   繁体   中英

How to calculate the max euclidean distance between two elements in a matrix - R?

I have a 100x100 matrix of 0's and 1's. I am trying to calculate the max euclidean distance between any 2 integers of 1 in the matrix.

Should I find the position of the two integer that are furthest apart from each other and use them?

Many thanks in advance

The simplest method would be the brute-force search over all possible points. This is doable because the size of the matrix is manageable:

set.seed(123)
m <- matrix(sample(c(1,0), size = 100^2, replace = TRUE), 100, 100)

max_dist <- 0
coord <- numeric()

for (i in 1:100){
  for (j in 1:100){
    for (k in 1:100){
      for (l in 1:100){
        if (m[i,j] == 1 && m[k,l] == 1){
          dist <- sqrt((i-k)^2+(j-l)^2)
          if (dist > max_dist){
            max_dist <- dist
            coord <- c(i,j,k,l)
          }
        }
      }
    }
  }
}

Here, we update the max distance and points' coordinates if encounter a pair of points whose distance is higher than the previous max and they are both equal to 1. In this example, the maximum distance is equal to 138.6 and the coordinates are (1,1) and (98,100).

Here is one approach that avoids looking at each element of the matrix by a for loop.

# set up
set.seed(123)
n <- 100
m <- matrix(sample(c(1,0), size = n^2, replace = TRUE), n, n)

# find the ones in the matrix and calculates the distances
ind <- which(m==1, arr.ind=TRUE)
dists <- dist(ind) # default euclidean

# look for the largest entry, and convert it to index position
ind1d <- which.max(dists)
ind2d <- arrayInd(ind1d, .dim=rep(nrow(ind),2))

# get answer
ans <- ind[as.vector(ind2d),]
ans

#     row col
#[1,]  98 100
#[2,]   1   1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM