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

1 vue (au cours des 30 derniers jours)
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+')

Réponses (1)

Image Analyst
Image Analyst le 21 Jan 2018
Modifié(e) : Image Analyst le 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 commentaires
Jenny
Jenny le 21 Jan 2018
Modifié(e) : Image Analyst le 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 le 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);

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by