Search code examples
matlabmatrixvoronoi

how to assign the dotes to which Voronoi cell belongs?


i want to know how to find that the indexes of dots that locates in each Voronoi cell.

for example (simply)

x=rand(2,6)*10
voronoi(x(1,1:3),x(2,1:3),'*')
hold on
plot(x(2,:),x(1,:),'o')

here there are 3 cells, i want to find which dot inside which cell


Solution

  • The Voronoi diagram is defined by a set of seed points. This induces a partitioning of the space into cells, with one cell per seed point. In your example, the seed points are the first 3 points in x. Each Voronoi cell contains the set of all points that are closer to its seed point than to any other seed point. For example, to determine which points are in cell 1, find the set of points that are closest to seed point 1.

    You can do this using knnsearch(). Following your example:

    % Seed points
    s = x(:, 1:3);
    
    % Find enclosing Voronoi cell for each data point
    idx = knnsearch(s', x', 'k', 1)
        % idx(i) = Index of nearest seed point to data point i
    

    Here, we're treating each column of x as a data point. The first row is the x coordinate and the second row is the y coordinate. This is the same as you used when calling voronoi(). But, I think you accidentally (?) swapped the x and y coordinates when calling plot(). We take the transpose when passing the matrices to knnsearch() because it expects rows to correspond to points and columns to dimensions.