Calculate minimum distance between points in a mesh
조회 수: 31 (최근 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
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:
채택된 답변
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
2019년 12월 28일
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
2019년 12월 28일
YOu may get your required code from this toolbox, try out.
추가 답변 (1개)
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)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Polar Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!