Determining if points lie within a sphere

I have a set of points P(x,y,z) and a sphere defined by its centre (x0,y0,z0) and radius r. I want to find the points that lie within or on the edge of sphere. I can run a loop for all points and check the condition:
(x-x0)^2+(y-y0)^2+(z-z0)^2<=r^2
But, Is there a direct function or any cheap method that would directly give me the indices of all points that lie within the sphere? Something I can easily use when there are large number of points and different sphere radius to test?
Thank you.

 Akzeptierte Antwort

Matt J
Matt J am 29 Sep. 2021
Bearbeitet: Matt J am 29 Sep. 2021

0 Stimmen

Do you really need the indices? You can readily obtain a logical mask of the points in the sphere with,
mask = (x-x0).^2+(y-y0).^2+(z-z0).^2<=r^2;
If you really do need the indices, then,
find(mask)

3 Kommentare

Vinit Nagda
Vinit Nagda am 29 Sep. 2021
Thanks for your response.
Yes, I need the indices. Each point carries some weight. I have to evaluate the mean of the weights of points that lie within the sphere.
Matt J
Matt J am 29 Sep. 2021
OK, but I showed you how to get the indices, so you have your answer. Please Accept-click the answer then, unless there is some unresolved issue.
Matt J
Matt J am 29 Sep. 2021
Bearbeitet: Matt J am 29 Sep. 2021
Yes, I need the indices. Each point carries some weight. I have to evaluate the mean of the weights of points that lie within the sphere.
Incidentally, that doesn't explain why you need the indices. You could instead just do,
mean(weightVector(mask))

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Mathematics finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2020b

Gefragt:

am 29 Sep. 2021

Bearbeitet:

am 29 Sep. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by