How to generate uniform random points with in a circle.
51 ビュー (過去 30 日間)
古いコメントを表示
I used "rand" function to generate uniform random points within the circle, but points generated by this code are not uniformly distributed. The code used by me is given below.So, is there any way to do so?? If any body know the answer please help me. Any suggestions will be appreciated. Thanks in advance.
Code:
% Create a random set of coordinates in a circle.
% First define parameters that define the number of points and the circle.
n = 400;
R = 20;
x0 = 0; % Center of the circle in the x direction.
y0 = 0; % Center of the circle in the y direction.
% Now create the set of points.
t = 2*pi*rand(n,1);
r = R*sqrt(rand(n,1));
x = x0 + r.*cos(t);
y = y0 + r.*sin(t);
% Now display our random set of points in a figure.
plot(x,y, 'o', 'MarkerSize', 5)
axis square;
grid on;
% Enlarge figure to full screen.
%set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
fontSize = 30;
xlabel('X', 'FontSize', fontSize);
ylabel('Y', 'FontSize', fontSize);
title('Random Locations Within a Circle', 'FontSize', fontSize);
1 件のコメント
Walter Roberson
2017 年 10 月 9 日
That code should distribute uniformly random by area.
Remember, "uniform random" does not mean "does not look like it has clusters or obvious open space". Humans see open areas and tend to say "Oh, it isn't uniformly randomly distributed" when it is.
It is like flipping a coin a million times in a row, seeing that at some point there was 15 Tails in a row, and saying "Oh, that's a huge gap, that isn't uniformly randomly distributed!" (indeed, you would expect to see about 17 to 21 Tails in a row if the coin was fair.)
採用された回答
その他の回答 (2 件)
abbas sabbagh
2022 年 3 月 3 日
編集済み: abbas sabbagh
2022 年 3 月 3 日
Hi, please check this code. It is really uniformly distributed!
clear;
clc;
clf;
Npoint=10000;
R=2;
for i=1:(5/pi)*Npoint, % generating more than points needed (greedy coeff is 4/pi)!
x=unifrnd(-R,R);
y=unifrnd(-R,R);
if x^2 + y^2 <=R^2,
XX(i,:)=[x,y];
end
end
XX( all(~XX,2), : ) = []; % deleting zeros rows
XX=XX(1:Npoint,:); % choosing the first valid Npoint generated
scatter(XX(:,1),XX(:,2),'.');
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!