均匀随机排布

2019-05-30 14:56:38 浏览数 (1)

%% 想要在给定区域内随机均匀分布一定数量的点

% 网上有这样的方式

load('usborder.mat','x','y','xx','yy');

figure

plot(x,y,'Color','red'); hold on;

plot(xx,yy,'b--')

cities = 40;

locations = zeros(cities,2);

n = 1;

while (n <= cities)

% 随机产生包络矩形区域内的点

xp = rand*1.5;

yp = rand;

if inpolygon(xp,yp,xx,yy)

% 如果在给定区域内就保留

locations(n,1) = xp;

locations(n,2) = yp;

n = n 1;

end

% 如果不在就继续

end

plot(locations(:,1),locations(:,2),'bo');

% 但是这样并不均匀

%% 有个科学的方式可以在凸多边形中均匀分布点

% 先在三角形内实现均匀

a = [1.0,0.5];

b = [0.7,0.2];

c = [0.3,0.8];

triangle = [a;b;c;a];

% 调用函数分布100个点

points = randTriangle([a;b;c],100);

figure

hold on

axis equal

plot(triangle(:,1),triangle(:,2))

scatter(points(:,1),points(:,2),100,'.')

text(triangle(:,1),triangle(:,2),['a';'b';'c'],...

'FontWeight','bold','FontSize',20)

%% 将凸多边形分割为多个三角形

polygone = [0,0;1,0;10,1;30,8;20,8;0,5] ;

% 调用函数分布100个点

points = randPolygone(polygone,100);

figure

hold on

axis equal

fill(polygone(:,1),polygone(:,2),'cyan','FaceAlpha',0.3)

scatter(points(:,1),points(:,2),100,'.')

text(polygone(:,1),polygone(:,2),['a';'b';'c';'d';'e';'f'],...

'FontWeight','bold','FontSize',20)

%% 但是只适用于凸多边形

load('usborder.mat','x','y','xx','yy');

polygone = [xx,yy];

points = randPolygone(polygone,100);

figure

hold on

axis equal

fill(polygone(:,1),polygone(:,2),'cyan','FaceAlpha',0.3)

scatter(points(:,1),points(:,2),100,'.')

% 可以试试把非凸多边形也进行分割

% 不过这好像不是一个简单问题

相关文件下载链接:https://pan.baidu.com/s/14fAaU4oj_cLXXzO5OJMC_Q

提取码:qz3l

0 人点赞