Recently Published
Plot
#Practice of K-D tree search
library(FNN)
#Define tha data points; (2,3),(5,4),(9,6),(4,7),(8,1),(7,2)
points <-matrix(c(
2,3,
5,4,
9,6,
4,7,
8,1,
7,2
), ncol=2, byrow=TRUE)
colnames(points) <- c("x","y")
#Plot the points for visualization
plot(points, col="blue", pch=19, xlab="x", ylab="y", main="2D points and query")
text(points, labels=1:nrow(points),pos=3)
#Define query point (9,2)
query_point <-matrix(c(9,2), ncol=2)
points(query_point, col="red", pch=4, cex=2)
text(query_point, labels="Query", pos=1)
#Perform KD tree nearest neighbor search using FNN
nn_result <- get.knnx(data=points, query=query_point, k=1)
#Output the nearest neighbor and distance
nearest_point <- points[nn_result$nn.index, ]
distance <- nn_result$nn.dist
cat("Nearest neighbor to (9,2) is: (", nearest_point[1], ",", nearest_point[2], ")\n")
cat("Distance to nearest neighbor:", distance, "\n")
#1.Construct 2-D tree
#2.Return distance from nearest neighbor to query point
#Distance=√(x1-x2)^2+(y1-y2)^2