Creating random points in a circle

I am new to MatLab but I am trying to write code for a problem and a couple of things are sticking me up. I am trying to create X number of random points within a circle. The purpose being to model a camp fire and map temperature from the center of the circle at the hottest to the outside. And I am lost. And I can't find an example anywhere I might be able to pull apart and work with. And help would be very much appreciated.
Thanks!

 Respuesta aceptada

Roger Stafford
Roger Stafford el 19 de Mayo de 2013
Let the circle be of radius R and center at (x0,y0). Let n be the desired number of points within.
t = 2*pi*rand(n,1);
r = R*sqrt(rand(n,1));
x = x0 + r.*cos(t);
y = y0 + r.*sin(t);
plot(x,y)

7 comentarios

I neglected to use a dot in the plot:
plot(x,y,'.')
axis equal
Image Analyst
Image Analyst el 31 de Jul. de 2013
Editada: Image Analyst el 31 de Jul. de 2013
Very nice code. I filled it out a little to make a complete demo. I added it to the FAQ.
% Create a random set of coordinates in a circle.
% First define parameters that define the number of points and the circle.
n = 5000;
R = 20;
x0 = 50; % Center of the circle in the x direction.
y0 = 90; % 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, '.', '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);
Adrian Blanco
Adrian Blanco el 20 de Mayo de 2016
Hi,
Thanks for the amazing examples. How would it be to create random points in a square? I am trying to change the math of the example but without success.
Thanks in advance for the advice.
Uniform random points in a square is easy.
x = rand(n,1);
y = rand(n,1);
Jan
Jan el 21 de Mzo. de 2018
rand() replies values from the open interval (0,1), such that t=0 or t=2*pi will never occur. The difference to the correct distribution over [0,1) or (0,1] is tiny, but it is a pity, that Matlab's RNG does not offer half-closed or closed intervals also.
Wen Wei
Wen Wei el 15 de Ag. de 2023
Editada: Wen Wei el 15 de Ag. de 2023
@Jan Whether you're sampling from a half-closed [0,1) or open (0,1) or closed [0,1] interval is irrelevant, since measure-theoretically the measure of the end points are 0. That is to say, the event (exactly t = 0 or t = 1) occuring has probability 0.
So your statement that the difference is "tiny" is not quite right: the difference is ignorable, in a rigorous mathematical sense. (See Wiki page on measure theory/probability theory)
Walter Roberson
Walter Roberson el 15 de Ag. de 2023
measure-theoretically the measure of the end points is not zero. None of the algorithms for rand() generates to infinite precision: they generate to at most 53 bits. The results of rand() are, at best, the same as the result of randi([1, 2^53-1]) / 2^53 . In terms of 53 bit precision, the 0 would be 1 value out of exactly 2^53 if you exclude 2^53 itself (because 0 to 2^53 is (2^53 + 1) distinct values); likewise if you exclude 0 but include 2^53 itself in the random integer to allow random value of exactly 1.0 to be generated, then that would be probability 1/2^53 . If you were to allow both exactly 0 and exactly 1 to be generated from rand, then the probability of 0 would be 1/(2^53+1) and likewise the probability of 1 would be the same.
The events (exactly t = 0 or t = 1) are only probability 0 if you are drawing from an infinite number of values... but you are not, since finite (fixed) precision results are being returned.

Iniciar sesión para comentar.

Más respuestas (2)

Image Analyst
Image Analyst el 20 de Abr. de 2013
Here, see my demo:
% M-file to place multiple points inside a big circle.
% Clean up
close all;
clc;
fontSize = 15;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
% Initialize some parameters.
numberOfPoints = 25; % Number of small circles
bigImageWidth = 500;
bigImageHeight = 500; % square area 0f 500*500
bigCircleRadius = 250; % big circle radius
% Initialize an image to hold one single big circle.
bigCircleImage = zeros(bigImageHeight, bigImageWidth, 'uint8');
[x, y] = meshgrid(1:bigImageWidth, 1:bigImageHeight);
bigCircleImage((x - bigImageWidth/2).^2 + (y - bigImageHeight/2).^2 <= bigCircleRadius.^2) = 1;
clear('x', 'y'); % Release these variables, they're not needed anymore.
% Display it in the upper left plot.
subplot(2,2, 1);
imshow(bigCircleImage, []);
title('Big Circle Mask', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
% Initialize an output image to hold many small overlapping circles.
pointsImage = zeros(bigImageHeight, bigImageWidth, 'uint8');
% Get linear indexes of 500 randomly located in the rectangle.
numberOfPointsToPlace = 5000;
linearIndexes = randi(numel(pointsImage), numberOfPointsToPlace, 1);
% Set those points in the image
pointsImage(linearIndexes) = 255;
% Get locations in terms of row and columns:
[rows, columns] = ind2sub(size(pointsImage), linearIndexes);
% Display it in the lower left plot.
subplot(2,2, 2);
imshow(pointsImage);
title('Many Points', 'FontSize', fontSize);
% Multiply the big circle mask by the points image to clip
% those points that lie outside the big circle.
maskedByBigCircle = bigCircleImage .* pointsImage;
% Display it in the lower right plot.
subplot(2,2, 3);
imshow(maskedByBigCircle);
title('Many Points Masked by Big Circle', 'FontSize', fontSize);

3 comentarios

Image Analyst
Image Analyst el 19 de Mayo de 2013
Stephen, what's the status of this? Are you still stuck?
Hello, this is similar to a problem i am facing, maybe you can help?
The code below is a function that asks for a radius, and then generates a circle with random points within +/-10% of the radius. It also generates 2 circles +and-5% from the original circle.
function missrate=Final_radiationring(r)
clc
theta=0:0.1:2*pi;
%r=20;
q='Enter radius: ';
r=input(q);
xcenter=0;
ycenter=0;
xcord= xcenter+r*cos(theta);
ycord=ycenter+r*sin(theta);
plot(xcord,ycord,'b')
hold on
xchigh=xcenter+(r+(r/20))*cos(theta);
xclow=xcenter+(r-(r/20))*cos(theta);
ychigh=ycenter+(r+(r/20))*sin(theta);
yclow=ycenter+(r-(r/20))*sin(theta);
plot(xchigh,ychigh, 'm')
plot(xclow,yclow, 'g')
n = 300;
x0 = 0; % Center of the circle in the x direction.
y0 = 0; % Center of the circle in the y direction.
% Create set of points
rng default
t = 2*pi*rand(n,1);
g = 0.9*r+0.2*r*rand(n,1); %generate random points in boundary
x = x0 + g.*cos(t);
y = y0 + g.*sin(t);
% Now display our random set of points in a figure with circle
d=sqrt((x.^2)+(y.^2));
plot(x,y,'*r')
hold off
axis equal
grid on;
d
end
the "d" variable gives the distances of each point from the center of the circle. My goal is to somehow index and plot the ones outside of the circles seperately from the ones inside the circles.
any help is greatly appreciated.
Try this:
% Demo by Image Analyst.
clc; % Clear the command window.
fprintf('Beginning to run %s.m ...\n', mfilename);
close all; % Close all figures (except those of imtool.)
clearvars;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
r = 2;
missrate=Final_radiationring(r);
fprintf('Done running %s.m\n', mfilename);
function [missrate, radiusList] = Final_radiationring(r)
missrate = 0;
% Make 360 points around the circle.
numCirclePoints = 360;
theta = linspace(0, 2 * pi, numCirclePoints);
% Get radius, ignoring the one passed in.
%r=20;
q='Enter radius: ';
r=input(q);
xcenter=0;
ycenter=0;
radiusList = [r, r + r/20, r - r/20];
xcord = xcenter + r * cos(theta);
ycord = ycenter + r * sin(theta);
plot(xcord, ycord, 'b-', 'LineWidth', 2)
hold on
xchigh=xcenter + radiusList(2)*cos(theta);
xclow=xcenter + radiusList(3)*cos(theta);
ychigh=ycenter + radiusList(2)*sin(theta);
yclow=ycenter + radiusList(3)*sin(theta);
plot(xchigh,ychigh, 'm-', 'LineWidth', 2)
plot(xclow,yclow, 'g-', 'LineWidth', 2)
grid on;
numRandomPoints = 300;
x0 = 0; % Center of the circle in the x direction.
y0 = 0; % Center of the circle in the y direction.
% Create a noisy set of points
rng default
t = 2 * pi * rand(numRandomPoints,1);
g = 0.9 * r + 0.2 * r * rand(numRandomPoints,1); %generate random points in boundary
x = x0 + g.*cos(t);
y = y0 + g.*sin(t);
% Now display our random set of points in a figure with circle
radialDistances = sqrt(x.^2 + y.^2);
colors = ['r', 'g', 'b', 'm']
radiusList = [0, sort(radiusList, 'ascend'), inf];
for k = 1 : length(radiusList) - 1
r1 = radiusList(k);
r2 = radiusList(k+1);
logicalIndexes = radialDistances >= r1 & radialDistances < r2;
thisx = x(logicalIndexes);
thisy = y(logicalIndexes);
thisColor = colors(k);
plot(thisx, thisy, '.', 'Color', thisColor, 'MarkerSize', 20)
end
hold off
axis equal
grid on;
radialDistances
end

Iniciar sesión para comentar.

Irfan
Irfan el 31 de Jul. de 2013

0 votos

Hi, Roger, Why did you use sqrt in r = R*sqrt(rand(n,1)); it should be without sqrt, is'nt ?

1 comentario

Roger Stafford
Roger Stafford el 31 de Jul. de 2013
That is untrue! Without the square root operation, the distribution of points within the circle will not be uniformly distributed throughout its interior. Just try it out with a large value of n, say, n = 1000 and see.
Think of it this way, Irfan. The area of a circle with the same center and with half the given radius, R, is one-fourth that of the larger circle. Therefore the probability that we get an r value less than or equal to R/2 should be one-fourth. That is, a 'rand' value of 1/4 should give rise to a value r = R/2. This is accomplished by taking the square root of the 'rand' value. A similar reasoning applies to other fractional circles.

Iniciar sesión para comentar.

Preguntada:

el 20 de Abr. de 2013

Comentada:

el 15 de Ag. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by