我试图绘制一个(10,000 x 10,000)六角形格子,它是随机的半黑色和半白色。我不知道如何将这个格子的六边形随机地填充为黑白色。(this is a sample of what i really want from this code but I couldn't make it.) 。代码(用matlab编写):
clc
x=input('enter the value of x: ');
y=input('enter the value of y: ');
r=input('enter the value of R: ');
n=input('enter the value of N: ');
d=sqrt(3*n)*r
axis([0 x 0 y ])
c=r;
v=30:60:390;
cv=r*cosd(v);
sv=r*sind(v);
for y=0:2:y
for w=0:2:x
line(w*sqrt(3)/2*c+cv,y*1.5*c+sv,'tag','h');
end
end
for m=1:2:y
for k=1:2:x
line(k*sqrt(3)/2*c+cv,m*1.5*c+sv,'tag','h');
end
end
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
您可以使用fill
并通过格子正确协调来实现所需的输出:
m = 100; % horizontal count
n = 50; % vertical count
blackratio = 0.5; % here you can choose the ratio of black hexagons
% parametric definition of a hexagon
t = (1/12:1/6:1)'*2*pi;
x = cos(t);
y = sin(t);
blacks = rand(m, n) < blackratio;
d=sqrt(3)/2;
figure;
hold on
for ii = 1:m
for jj = 1:n
if blacks(ii, jj)
% draw a black hexagon
fill(x + d*(mod(2*ii+jj, 2*m)), y+1.5*jj, 'k', 'EdgeColor', 'None')
else
% draw a white hexagon
fill(x + d*(mod(2*ii+jj, 2*m)), y+1.5*jj, 'w', 'EdgeColor', 'None')
end
end
end
axis equal tight off
使用此输出:
请注意,在笔记本电脑上使用100x50,需要6秒才能获得结果。对于1000x1000,我的计算机崩溃了。
我的代码中的第二个fill
函数用白色替换透明度。如果你没有透明而不是白色填充,你可以删除这部分代码并加快速度。
答案 1 :(得分:0)
您可以使用What is Vanilla JS?绘制多个填充多边形。这种方法比在循环中逐个fill
绘制六边形快得多。
m = 100; % horizontal count
n = 50; % vertical count
blackratio = 0.5; % here you can choose the ratio of black hexagons
blacks = rand(m, n) > blackratio;
hexcount = sum(blacks(:));
whitecount = m * n - hexcount;
% parametric definition of a hexagon
t = (1/12:1/6:1)' * 2 * pi;
x = cos(t);
y = sin(t);
% coordinates of all black hexagons
Xb = zeros(6, hexcount);
Yb = zeros(6, hexcount);
% coordinates of all white hexagons
Xw = zeros(6, whitecount);
Yw = zeros(6, whitecount);
d=sqrt(3)/2;
bcount = 0;
wcount = 0;
for ii = 1:m
for jj = 1:n
if blacks(ii, jj)
bcount = bcount + 1;
Xb(:, bcount) = x + d * (mod(2 * ii + jj, 2 * m));
Yb(:, bcount) = y + 1.5 * jj;
else
wcount = wcount + 1;
Xw(:, wcount) = x + d * (mod(2 * ii + jj, 2 * m));
Yw(:, wcount) = y + 1.5 * jj;
end
end
end
figure; hold on
patch(Xb, Yb, 'k', 'EdgeColor', 'None')
patch(Xw, Yw, 'w', 'EdgeColor', 'None')
axis equal off
这为您提供了所需的输出: