Uniform distribution of N points within a sphere
Show older comments
Hello, I'm trying to generate a uniform distribution of points within a spherical shell. I am able to generate a uniform distribution on the surface of a unit sphere using three gaussian random variables (normalized by sqrt(x^2+y^2+z^2), but am not sure how to convert this to an equal density distribution within the shell of some thickness, (d = r_outer - r_inner).
Answers (2)
Matt Fig
on 24 Jan 2011
Here is another solution which converts to Cartesian coordinates, though it does call the trig functions.
function [x,y,z] = rand_pick_sphere(n,a,b,X,Y,Z)
% Uniform points in a shell of inner radius a, outer radius b and center at
% (X,Y,Z)
% [x,y,z] = rand_pick_sphere(300,.5,.6); % 300 points in shell between
% r = .5 and r = .6, with center at origin.
if nargin==3
X = 0;
Y = 0;
Z = 0;
end
r1 = (rand(n,1)*(b^3-a^3)+a^3).^(1/3);
phi1 = acos(-1 + 2*rand(n,1));
th1 = 2*pi*rand(n,1);
% Convert to cart.
x = r1.*sin(phi1).*sin(th1) + X;
y = r1.*sin(phi1).*cos(th1) + Y;
z = r1.*cos(phi1) + Z;
2 Comments
Bruno Luong
on 24 Jan 2011
Few possible modifications on Matt's code:
r1 = (rand(n,1)*(b^3-a^3)+a^3).^(1/3);
cphi = -1 + 2*rand(n,1);
sphi = sqrt(1-cphi.^2);
th1 = 2*pi*rand(n,1);
z = r1.*cphi + Z;
r1 = r1.*sphi;
x = r1.*sin(th1) + X;
y = r1.*cos(th1) + Y;
Matt Fig
on 24 Jan 2011
That would certainly speed things up a bit. Thanks, Bruno.
Bruno Luong
on 24 Jan 2011
% a is inner radius
% b is outer radius
% is a number of points
a = 2;
b = 3;
n = 1000;
s = randn(3,n);
r = (rand(1,n)*(b^3-a^3)+a^3).^(1/3);
c = r./sqrt(sum(s.^2,1));
s = bsxfun(@times, s, c);
% Bruno
Categories
Find more on Mathematics in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!