How to draw random-size circles in square - non overlap?
3 次查看(过去 30 天)
显示 更早的评论
Hi. i have a question.
How can I change the conditions for the check range and look for a square or rectangle so that the circles do not go out of range? Thanks.
%% https://stackoverflow.com/questions/30822267/how-plot-a-messy-random-size-circles-in-matlab?answertab=active#tab-top
clear ; clc ; clf ;
% set number of circles to plot
n = 50;
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
radii(idx) = (10 + rand*(19-10))/100; % random Radius
pos(idx, :) = rand(1, 2)*3 + radii(idx); %random Position
if ((sqrt(sum(pos(idx, :).^2)) + radii(idx) ) < (3*sqrt(2))) ... % ensure we're inside the big circle!!! how can change to another shape????
&& ((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
%% Generate Area
% figure(2);
clf;
hold on
% set(gca, 'visible', 'off')
daspect([1, 1, 1])
rectangle(...
'Position',[0 0 3 3],...% % 'Curvature', [1 1],...% this is for Area
'FaceColor', 'w',...
'EdgeColor', [ 0, 0, 0]);
%% generate Circles
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],...% this is for shape in Area
'EdgeColor','k',...
'FaceColor', 'none');
end
0 个评论
回答(1 个)
Image Analyst
2019-1-25
Well, glad you finally came to the forum with the real MATLAB experts.
This has been discussed before. See this link
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Surface and Mesh Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!