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