[英]How to calculate the max euclidean distance between two elements in a matrix - R?
我有一個 0 和 1 的 100x100 矩陣。 我正在嘗試計算矩陣中任意 2 個 1 整數之間的最大歐幾里得距離。
我應該找到彼此相距最遠的兩個integer中的position並使用它們嗎?
提前謝謝了
最簡單的方法是對所有可能的點進行蠻力搜索。 這是可行的,因為矩陣的大小是可控的:
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)
}
}
}
}
}
}
在這里,如果遇到一對距離大於前一個最大值並且它們都等於1的點,我們會更新最大距離和點的坐標。在這個例子中,最大距離等於138.6,坐標為(1 ,1) 和 (98,100)。
這是一種避免通過 for 循環查看矩陣的每個元素的方法。
# 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.