Documentation |
This example shows how to create random points within the volume of a sphere, as described by Knuth [1]. The sphere in this example is centered at the origin and has a radius of 3.
One way to create points inside a sphere is to specify them in spherical coordinates. Then you can convert them to Cartesian coordinates to plot them.
First, initialize the random number generator to make the results in this example repeatable.
rng(0,'twister')
Calculate an elevation angle for each point in the sphere. These values are in the open interval, , but are not uniformly distributed.
rvals = 2*rand(1000,1)-1; elevation = asin(rvals);
Create an azimuth angle for each point in the sphere. These values are uniformly distributed in the open interval, .
azimuth = 2*pi*rand(1000,1);
Create a radius value for each point in the sphere. These values are in the open interval, , but are not uniformly distributed.
radii = 3*(rand(1000,1).^(1/3));
Convert to Cartesian coordinates and plot the result.
[x,y,z] = sph2cart(azimuth,elevation,radii); figure plot3(x,y,z,'.') axis equal
If you want to place random numbers on the surface of the sphere, then specify a constant radius value to be the last input argument to sph2cart. In this case, the value is 3.
[x,y,z] = sph2cart(azimuth,elevation,3);