function [xa, ya, index] = nearestConnection(x, y)
xa    = zeros(size(x));
ya    = zeros(size(y));
index = zeros(size(x));
% Find the initial point defined by the smallest X value:
[~, idx0] = min(x);
xa(1)     = x(idx0);
ya(1)     = y(idx0);
index(1)  = idx0;
x(idx0)   = NaN;   % Mask original point
y(idx0)   = NaN;
for k = 2:numel(x)
   dist     = (x - xa(k - 1)) .^ 2 + (y - ya(k - 1)) .^ 2;
   [~, idx] = min(dist);
   index(k) = idx;
   xa(k)    = x(idx);
   ya(k)    = y(idx);
   x(idx)   = NaN;
   y(idx)   = NaN;
end
end