Skip to content

Instantly share code, notes, and snippets.

@nathanntg
Created November 2, 2014 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanntg/3b8fbe0218507da0628c to your computer and use it in GitHub Desktop.
Save nathanntg/3b8fbe0218507da0628c to your computer and use it in GitHub Desktop.
Distribution of Nearest Neighbor
% number of random points to generate
number = 500;
x_dim = 100;
y_dim = 100;
% generate points
points = rand(number,2) * [x_dim 0; 0 y_dim];
% list of nearest neighbors
nearest_neighbors = nan(1, number);
% get nearest neighbor to each point
idx = 1:number;
for i = idx
others = (idx ~= i);
nearest_neighbors(i) = min(sqrt(sum(((ones(number - 1, 1) * points(i, :)) - points(others, :)) .^ 2, 2)));
end
% create a scatter plot
f_s = figure;
scatter(points(:, 1), points(:, 2));
xlim([0 x_dim]);
ylim([0 y_dim]);
% create a histogram
f_h = figure;
hist(nearest_neighbors);
ylabel('Distance to nearest neighbor');
title('Histogram');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment