manoos
manoos

Reputation: 1735

How to generate random points inside sphere using MATLAB

I tried to generate random points inside sphere by using following commands with center at origin by using following code

no_of_spots = 3000
radius=20
rvals = (2)*rand(no_of_spots,1)-(1);
elevation = asin(rvals);
azimuth = 2*pi*rand(no_of_spots,1);
radii = rand(no_of_spots,1)*radius;
[point_x,point_y,point_z] = sph2cart(azimuth,elevation,radii);

I got results as sphere with random points

From figure it is random points are concentrated near origin, ie looking like Gaussian distribution. I need random points distributed inside sphere uniformly or need to shift concentration of points from center to another point. How can I do that/ Can anyone help/ Thanks in advance, Manu

Upvotes: 4

Views: 971

Answers (1)

frslm
frslm

Reputation: 2978

If you tweak your radii line from:

radii = rand(no_of_spots,1)*radius;

To:

radii = (rand(no_of_spots,1).^(1/3))*radius;

You should get a more uniform-looking distribution.

This is what Knuth described in The Art of Computer Programming. Vol. 2 and is referenced here.

Upvotes: 5

Related Questions