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

1 次查看(过去 30 天)
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+')

回答(1 个)

Image Analyst
Image Analyst 2018-1-21
编辑:Image Analyst 2018-1-21
Instead of generating randomly located vertices, you need to put vertices for your hexagon. I assume you know how to do this.
  4 个评论
Jenny
Jenny 2018-1-21
编辑:Image Analyst 2018-1-21
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 2018-1-21
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);

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by