how to generate random points located on the surface of a hemisphere with its center at (2, 1, 3) and a radius of 6?

18 views (last 30 days)
N=500;
r = 6;
center = [2,1,3];
plot3(center(1),center(2),center(3),'ro')
hold on
for i=1:N
x1 = rand;
x2 = rand;
Px = sqrt(x1*(2-x1))*cos(2*pi*x2)+ center(1);
Py = sqrt(x1*(2-x1))*sin(2*pi*x2)+ center(2);
Pz = 1-x1 + center(3);
plot3(Px, Py, Pz,'o'),hold on
end
p = [Px, Py, Pz];
dist = Ddist(center,p);
What am I missing here? I'm using the dist variable to be sure I'll get 6, but currently I get 1

Accepted Answer

Jeremiah Abimbola
Jeremiah Abimbola on 30 Apr 2019
N=5000;
r = 6;
center = [2,1,3];
P = zeros(N,3) ;
plot3(center(1),center(2),center(3),'ro')
hold on
for i=1:N
x1 = rand;
x2 = rand;
Px = sqrt(x1*(2-x1))* cos(2*pi*x2);
Py = sqrt(x1*(2-x1))* sin(2*pi*x2);
Pz = 1-x1;
Px = Px * r + center(1);
Py = Py * r + center(2);
Pz = Pz * r + center(3);
P(i,:) = [Px, Py, Pz];
plot3(Px, Py, Pz,'o'),hold on
end

More Answers (2)

KSSV
KSSV on 23 Apr 2019
Use spherical coordinates,,,pick angles randomly and then convert into cartesian coordinates. Try this:
N=500;
r = 6;
center = [2,1,3];
plot3(center(1),center(2),center(3),'ro')
hold on
P = zeros(N,3) ;
for i=1:N
theta = randsample(linspace(0,2*pi),1);
phi = randsample(linspace(0,pi),1);
Px = center(1)+r*cos(theta)*sin(phi) ;
Py = center(2)+r*sin(theta)*sin(phi) ;
Pz = center(3)+r*cos(phi) ;
P(i,:) = [Px, Py, Pz];
end
hold on
plot3(P(:,1), P(:,2), P(:,3),'.r'),
% dist = Ddist(center,p);
  1 Comment
Jeremiah Abimbola
Jeremiah Abimbola on 23 Apr 2019
Edited: Jeremiah Abimbola on 23 Apr 2019
Yeah, this worked, but if i wanted to go by the code I provided, how can i do that? I see what you did there, radomizing the angles, but that's not the case for me. I tried to multiply x, y, z cordinates by the radius, but I got a distance greater than 6

Sign in to comment.


John D'Errico
John D'Errico on 30 Apr 2019
Edited: John D'Errico on 30 Apr 2019
Actually, there are easier ways than those proposed, with no loops required. The trick is easy too, basd on the symmetry of randn. I'll pick the hemisphere with x(:,1) positive.
N=500;
r = 6;
center = [2,1,3];
R = randn(N,3);
R(:,1) = abs(R(:,1));
R = r*R./sqrt(sum(R.^2,2)) + center;
The last line uses capabilities found in R2016b or later. Easrlier versions of MATLAB would use bsxfun, twice.
Plot the points to show they do indeed lie on a hemisphere.
plot3(R(:,1),R(:,2),R(:,3),'o')
axis equal
box on
grid on
xlabel x
ylabel y
zlabel z
I tried to rotate things around so the hemisphere was clear. If you do so, you will see the sphere is indeed hollow, so on the surface of a hemisphere.
Note that it took all of 3 lines to generate the list of points, far lesss than I spent in plotting them.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!