Calculate minimum distance between points in a mesh
16 views (last 30 days)
Show older comments
Assuming I have N points in a unit 2 or 3 dimensional box. How do I find the two points that are the closest and possible plot a circle around them?
So I am starting with randomly distributed points in 2D space:
A = rand(20, 2);
x = A(:, 1); % x coordinates
y = B(:, 2); % y coordinates
Now I want to find the minimum distance, print it and plot a circle around the two points to somehow mark them.
1 Comment
David Wilson
on 24 Apr 2019
Edited: David Wilson
on 24 Apr 2019
I assume you mean A(:,2) above. You could try pdist from the stats toolbox.
Something like:
A = rand(20, 2);
x = A(:, 1); % x coordinates
y = A(:, 2); % y coordinates
plot(x,y,'s')
D = pdist(A);
D = squareform(D);
D = D + max(D(:))*eye(size(D)); % ignore zero distances on diagonals
[minD,idx] = min(D(:));
[r,c]=find(D==minD);
hold on
plot(x(c), y(c), 'r*')
% Now plot a circle around the two points
c = [mean(x(c)), mean(y(c))]; % centerpoint
r = minD/2;
t = linspace(0,2*pi);
xc = r*exp(1j*t);
plot(real(xc)+c(:,1), imag(xc)+c(:,2),'r-')
hold off
axis equal
giving:
Accepted Answer
KSSV
on 24 Apr 2019
A = rand(20, 2);
x = A(:, 1); % x coordinates
y = A(:, 2); % y coordinates
d = pdist2(A,A) ;
% Get minimum distance
d(d==0) = NaN ;
[val,idx] = min(d(:)) ;
[i,j] = ind2sub(size(d),idx) ;
% plot circle
C = [mean(x([i j])) mean(y([i j]))] ;
R = val ;
th = linspace(0,2*pi) ;
xc = C(1)+R*cos(th) ;
yc = C(2)+R*sin(th) ;
plot(x,y,'.r')
hold on
plot(x(i),y(i),'+k')
plot(x(j),y(j),'+k')
plot(xc,yc,'b')
2 Comments
asasdasdasdadsadasd
on 28 Dec 2019
may I ask, how can we determine the minimum distance between two points in (one) each triangular element (3 nodes) in a very efficient way in Matlab?
Best
KSSV
on 28 Dec 2019
YOu may get your required code from this toolbox, try out.
More Answers (1)
Guillaume
on 24 Apr 2019
Here is one way:
points = rand(20, 2); %demo data
distance = hypot(points(:, 1) - points(:, 1).', points(:, 2) - points(:, 2).'); %distance between all points
distance(logical(tril(ones(size(distance))))) = Inf; %point below diagonal are symmetric of upper triangle. Also remove diagonal from minimum search
[mindistance, location] = min(distance(:));
[point1, point2] = ind2sub(size(distance), location);
fprintf('minimum distance of %g between point %d and %d\n', mindistance, point1, point2)
0 Comments
See Also
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!