Computes K nearest neighbors by Euclidean distance from an N x D PCA (or other embedding) matrix, without constructing the full N x N distance matrix. Optional same-group masking applies.
Arguments
- pca_matrix
Numeric matrix (N x D). Rows are samples, columns are embedding dimensions.
- K
Integer. Number of nearest neighbors. Must satisfy
1 <= K <= N - 1.- agroups
Integer vector of length N, or
NULL.NULLassigns unique groups (no masking).- bgroups
Integer vector of length N, or
NULL.- sort_nbrs
Logical. If
TRUE(default), sort K neighbors by ascending Euclidean distance.
Value
A list with two elements:
knn_indicesInteger matrix (N x K). 1-based indices.
knn_distancesNumeric matrix (N x K). Euclidean distances.