[英]How do you create a function to input two vectors to produce a matrix [R]
假設我有 5 對矢量形式的坐標 (x1,y1)(region1), (x2,y2)(region2) 等等,直到 (x5,y5)(region5)。 現在我想找到每個區域之間的距離。 例如,我取區域 i 和 j 之間的距離 D = √[(i−)^2+(−)^2],output 將是一個 5 x 5 矩陣,其中矩陣 (Dij) 中的每個條目是兩個區域之間的距離。
例如,我有區域 1,其坐標為 (4,3),區域 2 (1,2)。 那么這兩個區域之間的距離應該是 D = √10,這應該在 Dij 的條目中,其中 i =1 和 j=2,因此 D12 如上述矩陣所示。 我嘗試了如下所示的代碼:
x=c(1,2,4,1,1)
y=c(4,3,1,2,2)
Distance = function(x,y){
D = sqrt(abs((x[i]-x[j])^2+(y[i]-y[j])^2))
A = matrix(0,nrow=5,ncol=5,T)
i = nrow(A)
j = ncol(A)
for (i in 1:5){
for (j in 1:5){
A[i][j] = D
}
}
return(A)
}
Output:
Warning messages:
1: In A[i] <- `*vtmp*` :
number of items to replace is not a multiple of replacement length
其中有 20 條警告信息。 嘆。 我知道我的代碼遠非正確。 請幫忙
代碼存在以下問題。
代碼 -
Distance = function(x, y) {
stopifnot(length(x) == length(y))
n = length(x)
A = matrix(nrow = n, ncol = n)
for (i in 1:n) {
for (j in 1:n) {
A[i, j] = sqrt( (x[i] - x[j])^2 + (y[i] - y[j])^2 )
}
}
A
}
# test
x = c(1, 2, 4, 1, 1)
y = c(4, 3, 1, 2, 2)
Distance(x, y)
## [,1] [,2] [,3] [,4] [,5]
## [1,] 0.0000 1.4142 4.2426 2.0000 2.0000
## [2,] 1.4142 0.0000 2.8284 1.4142 1.4142
## [3,] 4.2426 2.8284 0.0000 3.1623 3.1623
## [4,] 2.0000 1.4142 3.1623 0.0000 0.0000
## [5,] 2.0000 1.4142 3.1623 0.0000 0.0000
請注意,這可以使用外部更緊湊地完成。
d <- function(i, j) sqrt((x[i] - x[j])^2 + (y[i] - y[j])^2)
n <- length(x)
outer(1:n, 1:n, Vectorize(d))
## [,1] [,2] [,3] [,4] [,5]
## [1,] 0.0000 1.4142 4.2426 2.0000 2.0000
## [2,] 1.4142 0.0000 2.8284 1.4142 1.4142
## [3,] 4.2426 2.8284 0.0000 3.1623 3.1623
## [4,] 2.0000 1.4142 3.1623 0.0000 0.0000
## [5,] 2.0000 1.4142 3.1623 0.0000 0.0000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.