% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/vcg.R
\name{vcg_kdtree_nearest}
\alias{vcg_kdtree_nearest}
\title{Find nearest \code{k} points}
\usage{
vcg_kdtree_nearest(target, query, k = 1, leaf_size = 16, max_depth = 64)
}
\arguments{
\item{target}{a matrix with \code{n} rows (number of points) and 2 or 3
columns, or a \code{mesh3d} object. This is the target point cloud where
nearest distances will be sought}

\item{query}{a matrix with \code{n} rows (number of points) and 2 or 3
columns, or a \code{mesh3d} object. This is the query point cloud where
for each point, the nearest \code{k} points in \code{target} will be sought.}

\item{k}{positive number of nearest neighbors to look for}

\item{leaf_size}{the suggested leaf size for the \code{K-D} tree; default is
\code{16}; larger leaf size will result in smaller depth}

\item{max_depth}{maximum depth of the \code{K-D} tree; default is \code{64}}
}
\value{
A list of two matrices: \code{index} is a matrix of indices of
\code{target} points, whose distances are close to the corresponding
\code{query} point. If no point in \code{target} is found, then \code{NA}
will be presented. Each \code{distance} is the corresponding distance
from the query point to the target point.
}
\description{
For each point in the query, find the nearest \code{k} points in target using
\code{K-D} tree.
}
\examples{

# 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



}
