MATLAB: I have 200 points which are randomly distributed in 16 equal size of grids in 2D & i know the coordinates of the center points. I want to calculate the nearest point of center & also coordinates of those points of each grid.

asked by archiStatistics and Machine Learning Toolbox

Best Answer

% Generate points
x5 = linspace(0,1,4+1);
y5 = linspace(0,1,4+1);
x4 = 0.5*(x5(1:end-1)+x5(2:end));
y4 = 0.5*(y5(1:end-1)+y5(2:end));
[X4x4,Y4x4] = ndgrid(x4,y4);
randXY = rand(200,2);
% Find the nearest point indices
ID = nearestNeighbor(delaunayTriangulation(randXY),[X4x4(:) Y4x4(:)]);
% Plot it
close all
plot(X4x4, Y4x4, '*r');
hold on
plot(randXY(:,1), randXY(:,2), '.');
for k=1:numel(X4x4)
plot([X4x4(k) randXY(ID(k),1)],[Y4x4(k) randXY(ID(k),2)]);
end
for i=1:length(x5)
xline(x5(i));
end
for j=1:length(y5)
yline(y5(j));
end
axis equal
axis([0 1 0 1]);
Related Question