Clear Filters
Clear Filters

How to generate uniform random points with in a circle.

42 views (last 30 days)
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 Comment
Walter Roberson
Walter Roberson on 9 Oct 2017
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.)

Sign in to comment.

Accepted Answer

Torsten
Torsten on 9 Oct 2017

More Answers (3)

abbas sabbagh
abbas sabbagh on 3 Mar 2022
Edited: abbas sabbagh on 3 Mar 2022
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 on 26 Jan 2019
Thank you so much !!

Moreno, M.
Moreno, M. on 20 Mar 2022
https://uk.mathworks.com/matlabcentral/fileexchange/108374-uniformly-distributed-points

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!