function idx = bp_near(pos, p, r) % BP_NEAR Beads near a point. % idx = bp_near(pos, p, r) returns the beads within distance r of point p % (1-by-3). With r = 0, or if no bead is that close, returns the nearest bead. if numel(p) == 2 p = [p(:)', 0]; end d = vecnorm(pos - p(:)', 2, 2); idx = find(d <= r); if isempty(idx) [~, idx] = min(d); end end