# Find nearest point in B with the smallest distance for each point in A
library(ravetools)
n <- 10
A <- matrix(rnorm(n * 2), nrow = n)
B <- matrix(rnorm(n * 4), nrow = n * 2)
result <- vcg_kdtree_nearest(
target = B, query = A,
k = 1
)
plot(
rbind(A, B),
pch = 20,
col = c(rep("red", n), rep("black", n * 2)),
xlab = "x",
ylab = "y",
main = "Black: target; Red: query"
)
nearest_points <- B[result$index, ]
arrows(A[, 1],
A[, 2],
nearest_points[, 1],
nearest_points[, 2],
col = "red",
length = 0.1)
# ---- Sanity check ------------------------------------------------
nearest_index <- apply(A, 1, function(pt) {
which.min(colSums((t(B) - pt) ^ 2))
})
result$index == nearest_index
Run the code above in your browser using DataLab