Reputation: 13
I've created this little code and have troubles to sum up the results of the loop. Somebody can help me with it?
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)
}
}
I get 8 numbers as result, but can only display the last of it
Upvotes: 1
Views: 2898
Reputation: 115465
You could also use the inbuilt dist
function and avoid all these nested for loops
dist
calculates the euclidean distance (the default from number of possibilities). This appears to be what you want.
See ?dist
for more details
# 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
Upvotes: 2
Reputation: 19454
Alternatively, you could use the outer
function (if someone comes up with a better way to vectorize the anonymous function, please feel free to edit)
(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
is used to index a
, and 1:2
is used to index b
.
Upvotes: 4
Reputation: 37814
You need to fill in your dist
matrix as you go.
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
Upvotes: 3