How can I modify this code below to generate random points inside a regular hexagon and then get the points in a vector?

2 views (last 30 days)
numEdges = 6;
xv = rand(numEdges,1);
yv = rand(numEdges,1);
xv = [xv ; xv(1)];
yv = [yv ; yv(1)];
numPointsIn = 20;
for i = 1:numPointsIn
flagIsIn = 0;
while ~flagIsIn
x(i) = rand(1);
y(i) = rand(1);
flagIsIn = inpolygon(x(i),y(i),xv,yv);
end
end
plot(xv,yv,x,y,'r+')

Answers (1)

Image Analyst
Image Analyst on 21 Jan 2018
Edited: Image Analyst on 21 Jan 2018
Instead of generating randomly located vertices, you need to put vertices for your hexagon. I assume you know how to do this.
  4 Comments
Jenny
Jenny on 21 Jan 2018
Edited: Image Analyst on 21 Jan 2018
I tried this way.
numEdges = 6; R = 8;
xv = R * cos((0:6)*pi/3);
yv = R * sin((0:6)*pi/3);
xv = [xv ; xv(1)];
yv = [yv ; yv(1)];
numPointsIn = 20;
for i = 1:numPointsIn
flagIsIn = 0;
while ~flagIsIn
x(i) = rand(1);
y(i) = rand(1);
flagIsIn = inpolygon(x(i),y(i),xv,yv);
end
end
plot(xv,yv,x,y,'r+')
Image Analyst
Image Analyst on 21 Jan 2018
Try this:
numEdges = 6;
R = 8;
xVertex = R * cos((0:6)*pi/3);
yVertex = R * sin((0:6)*pi/3);
xVertex = [xVertex , xVertex(1)];
yVertex = [yVertex , yVertex(1)];
requiredPoints = 20;
plot(xVertex, yVertex, 'b+-', 'LineWidth', 3);
grid on;
numPointsIn = 1;
while numPointsIn < requiredPoints
testx = 2 * R * rand(1) - R;
testy = 2 * R * rand(1) - R;
if inpolygon(testx, testy, xVertex, yVertex)
x(numPointsIn) = testx;
y(numPointsIn) = testy;
numPointsIn = numPointsIn + 1;
end
end
hold on;
plot(x,y,'r+', 'MarkerSize', 10, 'LineWidth', 2);

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!