categorize points by distance
1 view (last 30 days)
Show older comments
I have 51 points(x,y) that represent locations, four of them are the main locations(stores) to which the rest of the locations must be divided by distance (for example locations 4,6,18,33 etc are closer to store 1, locations 5,19,22, etc closer to store 2 and 48,46.7 etc to store 3) . I already made a matrix 51x51 that represents the distances among all points (using the euclidean distance) if it's better to work like that , but how can i do it?
0 Comments
Answers (2)
Image Analyst
on 29 Dec 2019
How did you create the 51x51 matrix? Using pdist2()?
Why not just use the 4 if that's what you want?
distances = pdist2(xy51Points, xy4Points);
I'm not really sure what you want as the output? Do you want to somehow categorize the distances into classes (ranges), like class #1 is 0-10 km away, class #2 is 10-20 km, etc.
6 Comments
Image Analyst
on 29 Dec 2019
Is this what you want?
% Define our 4 reference points.
xy4 = rand(4, 2);
% Define our 47 other points.
xy47 = rand(47, 2);
% Plot them
plot(xy4(:, 1), xy4(:, 2), 'r.', 'MarkerSize', 15);
grid on;
hold on;
plot(xy47(:, 1), xy47(:, 2), 'b.', 'MarkerSize', 15);
% Find the distance from every one of the 4 reference points
% to every one of the 47 other points.
distances = pdist2(xy4, xy47)
% Find the index and distance of the closest of the other 47 to each reference point.
for k = 1 : size(xy4, 1)
[closestDistance(k), closestIndex(k)] = min(distances(k,:));
fprintf('The closest point to reference point #%d is #%d with a distance of %f.\n', ...
k, closestIndex(k), closestDistance(k));
% Draw a line connecting them
line([xy4(k, 1), xy47(closestIndex(k), 1)], [xy4(k, 2), xy47(closestIndex(k), 2)], ...
'LineWidth', 2, 'Color', 'm');
end
xlabel('X', 'FontSize', 20);
ylabel('Y', 'FontSize', 20);
fprintf('Done!\n');
![0000 Screenshot.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/257528/0000%20Screenshot.png)
Walter Roberson
on 29 Dec 2019
Use pdist2() between the locations of the stores and the rest of the locations. Ue the two-output form of min() to find the index of the closest store for each of the 47 points.
See Also
Categories
Find more on Matrices and Arrays 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!