如何在MATLAB中绘制一个杂乱的随机大小的圆圈?

时间:2015-06-13 18:42:01

标签: matlab plot matlab-figure

我将在MATLAB R2014b中绘制如下图所示的数字:Messy Circles

此图由许多具有不同(随机)颜色和随机大小的圆圈组成。

如何在MATLAB R2014b中绘制这样的图?

2 个答案:

答案 0 :(得分:3)

没有拼写代码:

  1. 选择初始圈,例如位置[0,0]和半径1。
  2. 位置和半径的初始化列表。
  3. 选择随机位置和半径r
  4. 如果圈子不大(即sqrt(pos(1)^2+pos(2)^2) + r > 1)继续3。
  5. 如果与其他圆重叠(位置之间的距离>半径之和),请继续3
  6. 添加圆圈到列表,继续3
  7. 更新:示例

    好吧,所以我只想尝试一下。我确信这不是最好的实现,但是:

    % set number of circles to plot
    n = 200;
    radii = zeros(n, 1);
    pos = zeros(n, 2);
    allColours = lines(n);
    % main loop
    for idx = 1:n
        is_good = false;
        % generate random positions and radii until we have a hit
        while ~is_good
            pos(idx, :) = rand(1, 2)*2 - 1;
            radii(idx) = rand * (1 - max(radii));
            if ((sqrt(sum(pos(idx, :).^2)) + radii(idx) ) < 1) ... % ensure we're inside the big circle
                    && ((idx == 1) || ... %  and either it's the first circle, or
                    all(sqrt(sum((pos(1:(idx-1), :) - repmat(pos(idx, :), idx-1, 1)).^2, 2)) > radii(1:(idx-1))+radii(idx))) % all distances are bigger than sum of radii of existing circles
                is_good = true;
            end
        end
    end
    %% plot
    figure(2);
    clf;
    
    hold on
    set(gca, 'visible', 'off')
    daspect([1, 1, 1])
    rectangle(...
        'Position',[-1 -1 2 2],...
        'Curvature', [1 1],...
        'FaceColor', 'none',...
        'EdgeColor', [ 0, 0, 0]);
    for idx = 1:n
        rectangle(...
            'Position',[pos(idx, 1) - radii(idx), pos(idx, 2) - radii(idx), 2*radii(idx), 2*radii(idx)],...
            'Curvature', [1 1],...
            'EdgeColor','none',...
            'FaceColor', allColours(idx,:));
    end
    

    Example output

答案 1 :(得分:0)

总体思路如下。您需要对其进行修改,以确保选择圆心和颜色以适合您的特定目的。

% Define parameters
maxAxis = 100;
maxRadius = 10;
nCircles = 20;
% Random centres
xLoc = randi(maxAxis,nCircles);
yLoc = randi(maxAxis,nCircles);
% Random radii
radius = randi(maxRadius,nCircles);
% Random colours
allColours = rand(nCircles,3);
% Transform the data into position = [left bottom width height]
pos = [xLoc(:)-radius(:) yLoc(:)-radius(:) 2*radius(:)*[1 1]];
% Create and format the axes
ha = axes;
hold on;
axis equal;
box on;
set(ha,'XTickLabel',[],'YTickLabel',[]);
% Create the circles (must be done in loop)
for idx = 1:nCircles
    rectangle(...
        'Position',pos(idx,:),...
        'Curvature',[1 1],...
        'FaceColor',allColours(idx,:),...
        'EdgeColor','none');
end

>> doc retangle

了解更多信息。