Spread a random user in hexagonal cell
1 次查看(过去 30 天)
显示 更早的评论
Hello,i drawn one hexagonal cells and I want to spread a random users in it and specify the coordinates of each user in an array. thats my trial :
clear all;
close all;
clc;
t=linspace(0,2*pi,7);
x=0+1*cos(t);
y=0+1*sin(t);
plot(x,y);
hold on
grid on;
for i=1:100
xa=-0.8+1.6*rand(1,1);
ya=-0.8+1.6*rand(1,1);
xra(i)=xa;
yra(i)=ya;
figure(1)
plot(xra(i),yra(i),'k.');
hold on
end
as u see the whole cell cannot be filled by the users ,
Thanks for ur help :)
0 个评论
采纳的回答
Walter Roberson
2012-1-27
When you are choosing xa and ya, you are choosing the coordinates from a square from [-0.8, 0.8] in both x and y. Your hexagon extends a bit past +/- 0.8 in y, and extends to +/- 1 in x, and because of the angled lines there are parts of the square (whose coordinates you are choosing from) that are not within the hexagon.
The square: because -0.8+1.6*rand(1,1) ranges from -0.8 + 1.6*0 to -0.8 + 1.6 * 1 which is -0.8 to +0.8, and you use that calculation for both x and y.
You need to find a way of choosing exactly withinin the hexagon, or you need to find a way of choosing over a larger area and discarding the points that are not in the hexagon.
3 个评论
Walter Roberson
2012-1-28
http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
Walter Roberson
2012-1-28
Hint: http://www.mathworks.com/help/techdoc/ref/inpolygon.html
There is even a relevant example.
更多回答(1 个)
Ahmed Ibrahim
2016-5-6
编辑:Ahmed Ibrahim
2016-5-6
this is an update for your code:
-----------------------------------
function [xra,yra]=hex_rand(R,i)
% R is the hexagon side length
% i is the number of samples
t=linspace(0,2*pi,7);
x=0+R*cos(t);
y=0+R*sin(t);
plot(x,y);
hold on
grid on;
for m=1:i
xa=x(1)*2*(rand()-1/2);
ya=y(2)*2*(rand()-1/2);
if ((xa>(R/2)) && (ya>(-sqrt(3)*xa+(R*sqrt(3))))) %%the areas where the problem occur
ya=-sqrt(3)*xa+(R*sqrt(3));
elseif ((xa>(R/2)) && (ya<(sqrt(3)*xa-(R*sqrt(3)))))
ya=sqrt(3)*xa-(R*sqrt(3));
elseif ((xa<(-R/2)) && (ya>(sqrt(3)*xa+(R*sqrt(3)))))
ya=sqrt(3)*xa+(R*sqrt(3));
elseif ((xa<(-R/2)) && (ya<(-sqrt(3)*xa-(R*sqrt(3)))))
ya=-sqrt(3)*xa-(R*sqrt(3));
end
xra(m)=xa;
yra(m)=ya;
figure(1)
end
plot(xra,yra,'k.');
hold on
end
2 个评论
AMAL ALGEDIR
2016-7-10
编辑:AMAL ALGEDIR
2016-7-10
how I can change this code if the center of the hexagon is not (0,0). how I can make work with more than one cell? I could draw more than one cell but I could not fix the position od users?
Walter Roberson
2016-7-10
It is often easiest to generate the numbers around an origin of 0 and then add the center as the last step.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!