如何绘制NxN圆圈阵列?

时间:2018-02-11 08:15:24

标签: arrays matlab

我想绘制一个NxN圆圈阵列。为了形象化,我附上了我想要实现的图像。我是MatlLab的新手,所以我先尝试绘制一个圆圈,下面是示例代码:

n = 2^10;                   % size of mask
M = zeros(n);
I = 1:n;
x = I - n/2;                % mask x - coordinates
y = n/2 - I;                % mask y - coordinates
[X,Y] = meshgrid(x,y);      % create 2-D mask grid
R = 200;                     % aperture radius
A = (X.^2 + Y.^2 <= R^2);   % Circular aperture of radius R
M(A) = 1;                   % set mask elements inside aperture to 1
imagesc(M)                  % plot mask
axis image

我真的不知道如何绘制2D圆阵列。两个圆之间的距离是两个半径。我的研究需要这个。希望任何人都可以提供帮助。A 4 x 4 array of circles.

1 个答案:

答案 0 :(得分:6)

如果您只想绘制一组圆圈,可以在循环中使用rectangle函数

如果在调用rectangle时将Curvature属性设置为1,则会将其绘制为圆圈(参见文档)。

在循环中,您可以通过定义lower left坐标及其widthheight来正确设置每个矩形(圆圈)的位置。

使用n定义圆圈数并使用d直径,您可以将lower left坐标集计算为:

px=linspace(0,d*(nc-1),nc)
py=linspace(0,d*(nr-1),nr)

可以通过设置轴的颜色或绘制另一个矩形来获得黑色背景。

然后,您可以设置xlimylim以适应外部矩形。

你也可以通过设置○可见property to关闭来使axex不可见。

编辑#1

更新代码以允许绘制用户定义的圆圈数(设置行数和列数)

% Define the number of circles
% Number of rows
nr=8
% NUmber of column
nc=8
% Define the diameter of the circle
d=6
% Create an axex and set hold to on
ax=axes
hold on
% Evalaute the lower left position of each circle
px=linspace(0,d*(nc-1),nc)
py=linspace(0,d*(nr-1),nr)

% Plot the background rectangle
rectangle('Position',[px(1),py(1),d*nc,d*nr],'Curvature',[0 0],'facecolor','k')
% Plot all the circles
for i=1:length(px)
   for j=1:length(py)
      rectangle('Position',[px(i) py(j) d d],'Curvature',1,'facecolor','w')
   end
end
% Set the aspect ratio of the axes
daspect([1 1 1])
% Set the XLim and YLim
xlim([px(1) d*nc])
ylim([py(1) d*nr])
% Make the axes invisible
ax.Visible='off'

enter image description here

编辑#2

解决OP评论的替代解决方案:

如果我想让轴固定,比如我想要一个1024×1024的网格,(图像大小与圆半径无关)我该如何将它合并到代码中? < / p>

如果您想使用固定的(1024 x 1024)面具来绘制圆圈,请从您在问题中发布的cde开始,您只需执行以下操作:

  • (1024 x 1024)掩码上定义您想要绘制的圆圈数量2, 4, 8, ...
  • 定义一个只包含一个圆圈的基本面具
  • 识别该圈内的点并将其设置为1
  • 复制(使用函数repmat根据要绘制的圆圈数量的基本蒙版

根据您的代码实现可能是:

% Define the number of circles to be plotted
% on a (1024 x 1024) mask they can be 2, 4, 8, ...
n_circles=4
% Define the size of the basic mask
n0 = (2^10)/n_circles;
% Initialize the basic mask
M0 = zeros(n0);
% Define the x and y coordinates of the basic mask
I = 1:n0;
x = I - n0/2;
y = n0/2 - I;
% Create the mask
[X,Y] = meshgrid(x,y);
% Define the radius of the basic circle
R = n0/2;
% Get the indices of the points insiede the basic circle
A = (X.^2 + Y.^2 <= R^2);
% Set basic mask
M0(A) = 1;
% Open a FIgure
figure
% Replicate the basic mask accoding to the numner of circles to be plotted
M=repmat(M0,n_circles,n_circles);
% Display the mask
imagesc(M)
% Set the axes aspect ratio
daspect([1 1 1])