1

我已经创建了这个小代码,并且无法总结循环的结果。有人可以帮我吗?

a = array(c(1,1,1,1,1,1,1,2,1,1,1,1,1), dim=c(4,3))
b = array(c(0,0,0,0,0,1), dim=c(2,3))

dist <- array()
for (j in 1:2) { 
  for (i in 1:4) {
  dist <- sqrt (sum ((a[i, ]-b[j, ])^2))
  print(dist)
  }
}

结果我得到8个数字,但只能显示最后一个

4

3 回答 3

4

或者,您可以使用该outer函数(如果有人想出更好的方法来矢量化匿名函数,请随时编辑)

(dist <- outer(1:4, 1:2, FUN = Vectorize(function(x,y)sqrt(sum((a[x,]-b[y,])^2)))))
         [,1]     [,2]
[1,] 1.732051 1.414214
[2,] 1.732051 1.414214
[3,] 1.732051 1.414214
[4,] 2.449490 2.236068

1:4用于索引a1:2用于索引b

于 2012-08-16T14:43:33.200 回答
3

您需要随时填写dist矩阵。

dist <- array(dim=c(4,2))
for (j in 1:2) {
  for (i in 1:4) {
    dist[i,j] <- sqrt (sum ((a[i,1:3]-b[j,1:3])^2))
  } 
}
dist
于 2012-08-16T14:34:28.640 回答
2

您还可以使用内置dist函数并避免所有这些嵌套的 for 循环

dist计算欧几里德距离(可能性数量的默认值)。这似乎是你想要的。

查看?dist更多详情

# give a and b some rownames

row.names(a)  <- paste0('a',1:nrow(a))
row.names(b)  <- paste0('b',1:nrow(b))
#combine into one matrix
ab <- rbind(a,b)

# get the distance between the points

distances <- as.matrix(dist(ab))

# subset those you are interested in
distances[row.names(a),row.names(b)]

##           b1       b2
## a1 1.732051 1.414214
## a2 1.732051 1.414214
## a3 1.732051 1.414214
## a4 2.449490 2.236068
于 2012-08-17T03:41:59.137 回答