MATLAB: I have used the following code to create a wsn structure wth 4*4 cell grids and have randomly deployed 100 nodes in it.

cell headernodeswireless sensor network

I have used the following code to create a wsn structure with 4*4 cell grids and have deployed randomly 100 nodes in it.Now i want to elect cell-headers with the criteria that the node closest to mid-point of the cell is elected as cell-header. How to do it? Please help
NrGrid = 4; % Number Of Grids
x = linspace(0, 100, NrGrid+1);
[X,Y] = meshgrid(x);
figure(1)
plot(X,Y,'k')
hold on
plot(Y,X,'k')
hold off
set(gca, 'Box','off', 'XTick',[], 'YTick',[])
axis square
NrGrid = 4;
coords = rand(100,2) * maNrGrid + 1;
scatter(coords(:,1),coords(:,2));
set(gca, 'XTick', 1:maNrGrid+1, 'YTick', 1:maNrGrid+1)
grid on

Best Answer

[XC, YC] = ndgrid(1/2:NrGrid+1/2, 1/2:NrGrid+1/2);
center_idx = zeros(NrGrid, NrGrid);
for K = 1 : numel(XC)
xc = XC(K);
yc = YC(K);
dists = sqrt((coords(:,1)-xc).^2 + (coords(:,2)-yc).^2);
[mindist, minidx] = min(dists);
center_idx(K) = minidx;
end
Now center_idx will be a 4 x 4 array where each entry gives the row number in coords() of the node that is the closest to the center of the cell. For example if the entry at (2,4) says 73 then coords(73,:) would be the node closest to the center of the grid that goes 2..3 in X and 4..5 in Y.