Calculate minimum distance between points in a mesh

17 次查看(过去 30 天)
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 个评论
David Wilson
David Wilson 2019-4-24
编辑:David Wilson 2019-4-24
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:
tmp.png

请先登录,再进行评论。

采纳的回答

KSSV
KSSV 2019-4-24
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 个评论
asasdasdasdadsadasd
asasdasdasdadsadasd 2019-12-28
Dear @ KSSV,
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

请先登录,再进行评论。

更多回答(1 个)

Guillaume
Guillaume 2019-4-24
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)

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

标签

产品


版本

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by