MATLAB: Points too close XY space

distancepdist2Statistics and Machine Learning Toolbox

Hello,
I have a set of N points with coordinates (x1,y1)…(xN, yN). I would like to find the pairs that are closer than DX in X and closer than DY in Y, avoiding for-loops. Thanks in advance for any help!

Best Answer

Here is a solution that shows you all pairs of points where delta x is less than 0.2:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
% Define number of points.
N = 50;
% Get random x,y coordinates for those points.
x = rand(N, 1);
y = rand(N, 1);
subplot(2, 2, 1);
plot(x, y, 'b.', 'MarkerSize', 18);
grid on;
% Get distance of every point to every other point.
distances = pdist2(x, x);
% Find points closer than some specified distance to each other.
closestAllowableDistance = 0.02;
closePairs = distances < closestAllowableDistance;
subplot(2, 2, 2);
imshow(closePairs, []);
axis on;
xlabel('Column Index');
ylabel('Row Index');
% Show circles around pairs that are close

subplot(2, 2, 3);
plot(x, y, 'b.', 'MarkerSize', 18);
grid on;
hold on;
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Get rid of tool bar and pulldown menus that are along top of figure.
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
% Show circles around pairs that are close
hPair = plot(0, 0); % Initialize so we have something to delete the first time though the loop.
for col = 1 : N
for row = 1 : col-1
% Plot this point
if closePairs(row, col)
% The pair is close, so plot it.
x1 = x(row);
y1 = y(row);
x2 = x(col);
y2 = y(col);
% Delete old point
delete(hPair);
% Plot next point.
hPair = plot([x1, x2], [y1, y2], 'ro', 'MarkerSize', 13, 'LineWidth', 2);
% Tell them how far apart they are, and ask them if they want to continue.
promptMessage = sprintf('This pair is separated by %f\n\nDo you want to Continue processing,\nor Quit processing?',...
distances(row, col));
titleBarCaption = 'Continue?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Continue', 'Quit', 'Continue');
if strcmpi(buttonText, 'Quit')
return;
end
end
end
end
Related Question