function [Rmin] = mindist(x,y,z,X,Y, Z)

%R = zeros(size(x));
R = inf;
idx = NaN;
for n = 1:length(x)
    
    %%
    % Find the distance to all points on the surface, note that I'm not
    % conducting the sqrt here because the calculation is unneccesary.
    dists = ((x(n)-X).^2 + (y(n)-Y).^2 + (z(n)-Z).^2 );
    %R(n) = min(min(dists));
    Ri = min(min(dists));
    if Ri < R
        R = Ri;
        idx = n;
    end
end

%[~, idx] = min(R);
if isnan(idx)
    Rmin = NaN;
else
    Rmin = sqrt( ...
        (x(end)-x(idx)).^2 + ...
        (y(end)-y(idx)).^2 + ...
        (z(end)-z(idx)).^2 ...
        );
end


