How to generate uniform random points with in a circle.

73 次查看(过去 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
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.)

请先登录,再进行评论。

采纳的回答

Torsten
Torsten 2017-10-9

更多回答(2 个)

abbas sabbagh
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),'.');

Nguyen Duc Du
Nguyen Duc Du 2019-1-26
Thank you so much !!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by