Reputation: 2980
I have a function (copied from the MATLAB documentation) which generates random points inside a sphere. However, some points inside the sphere are not permissible. How can I generate random points inside a hollow sphere with permissible radius 1<r<2
. In other words, the points should lay on a radius of 1 to 2 so no points are allowed between r = [0 1].
EDIT: Completely forgot to include the function
function [x,y,z] = PointsInSphere(r,n)
rvals = 2*rand(n,1)-1;
elevation = asin(rvals);
azimuth = 2*pi*rand(n,1);
radii = r*(rand(n,1).^(1/r));
[x,y,z] = sph2cart(azimuth,elevation,radii);
end
Upvotes: 2
Views: 299
Reputation: 112769
Substitute the line
radii = r*(rand(n,1).^(1/r));
by
x = (s/r)^r;
radii = r*(x+(1-x)*rand(n,1)).^(1/r);
where r
is the outer radius and s
is the inner radius (new function argument).
This replaces the (0
,1
)-uniform variable that was used for obtaining the radii in the original function by an (x
,1
)-uniform variable. The value x
is computed such that the obtained radii have the original distribution but truncated to the interval (s
,r
). This ensures that the resulting 3D-distribution is uniform on the desired region.
Upvotes: 1
Reputation: 1490
You can easily generate 2 random numbers between 0 and 1. Use the first as radius (add 1 to it so it is in [1,2]). Multiply the second random number with 2pi. Convert that from polar to Cartesian coordinates and you should be done.
Edit: do the same with a second angle to move to 3D.
Upvotes: 0