vec_mat_dist: Euclidean distance from a single vector to each row of a matrix
Description
Calculates the Euclidean distance between a reference vector
v and every row of a matrix mat. This is a thin wrapper around
rowSums() and avoids an explicit loop, so it is fast even for large
matrices.
Usage
vec_mat_dist(v, mat)
Value
A numeric vector of length n containing the Euclidean distance
between v and each corresponding row of mat.
Arguments
v
Numeric vector of length d. The reference point in d-dimensional
space.
mat
Numeric matrix with n rows and d columns. Each row is treated
as a point whose distance from v is to be computed.
The number of columns in mat must match length(v).
Details
Internally the function replicates v into an \(n \times d\) matrix, subtracts it
from mat, squares the element-wise differences, sums across columns, and
finally takes the square root, i.e.
$$d_i = \sqrt{\sum_{k=1}^d (m_{ik} - v_k)^2}$$
for each row i.
Because the computation is fully vectorised it is considerably faster than a
simple apply() or a for-loop implementation.