MATLAB: I am trying to generate uniformly distributed points inside a hexagon of specific centre (other than the origin). Any help is most welcome, thank you.

helphexagon

I have seen codes like this with origin as centre only, but i need to apply it for hexagonal cells of different centres.

Best Answer

Define the centre points, then add them as appropriate to ‘v_x’ and ‘v_y’ and ‘c_x’ and ‘c_y’:
xcntr = 7; % X-Coordinate Of Centre Of Hexagon & Points

ycntr = 5; % Y-Coordinate Of Centre Of Hexagon & Points

...
v_x = R * cos((0:6)*pi/3) + xcntr;
v_y = R * sin((0:6)*pi/3) + ycntr;
...
c_x = R-rand(1, 3*N)*2*R + xcntr;
c_y = R-rand(1, 3*N)*2*R + ycntr;
In context:
N = 400; %Number of users
R = 10; %Radius of Hexagon
xcntr = 7; % X-Coordinate Of Centre Of Hexagon & Points
ycntr = 5; % Y-Coordinate Of Centre Of Hexagon & Points
%Define the vertexes of the hexagon. They for angles 0, 60, 120, 180, 240 and 300 withe origin.
%Vertexes
v_x = R * cos((0:6)*pi/3) + xcntr;
v_y = R * sin((0:6)*pi/3) + ycntr;
%The method used here is to generate many points in a square and choose N points that fall within the hexagon
%Generate 3N random points with square that is 2R by 2R
c_x = R-rand(1, 3*N)*2*R + xcntr;
c_y = R-rand(1, 3*N)*2*R + ycntr;
%There is a command in MATLAB inploygon.
%The command finds points within a polygon region.
%get the points within the polygon
IN = inpolygon(c_x, c_y, v_x, v_y);
%drop nodes outside the hexagon
c_x = c_x(IN);
c_y = c_y(IN);
%choose only N points
idx = randperm(length(c_x));
c_x = c_x(idx(1:N));
c_y = c_y(idx(1:N));
plot(c_x, c_y, 'r*');
hold on;
plot(v_x,v_y);
hold off
axis equal
axis([-1 1 -1 1]*20)