# Selecting elements from nested list based on condition

Assume that I have a nested list of the form

d = 0.1;
v = Table[{x, y, z}, {x, -1, 1, d}, {y, -1, 1, d}, {z, -1, 1, d}];


How do I select all elements {x,y,z} of this list that satisfy the condition x^2+y^2+z^2≤1?

In my search for possible implementations I've come across similar questions that have been answered using either "Select[]", "Extract[]", or "Cases[]", but even after looking at their documentations I just cannot seem to get the syntax right.

res=
Join @@@ (v /. {a_, b_, c_} /; a^2 + b^2 + c^2 > 1 :> Nothing)


Proof

And @@ (#1^2 + #2^2 + #3^2 <= 1 & @@@ Flatten[res, 1])


True

flat = Flatten[res, 1]


(* outputs 4169 triples *)

As a oneliner with the desired flatness:

Cases[#, {__Real}, -1] & @
ReplaceAll[{a_, b_, c_} /; a^2 + b^2 + c^2 > 1 :> Nothing] @ v

• Thanks, but how can I get this result in a list that is nested such that res={{x1,y1,z1},{x2,y2,z2},{x3,y3,z3},...} without any other nestings/brackets separating the three-element lists? Commented Nov 9, 2023 at 7:48
– eldo
Commented Nov 9, 2023 at 7:52
• Excellent, thank you! Would you mind explaining the meaning of "a_Real" (i.e. why not just "a_")? Also, what is the meaning of the parenthesis with ":>"? Commented Nov 9, 2023 at 7:53
• a_Real wasn't necessary, so I deleted it (good observation). :> stands for RuleDelayed (see Documentation)
– eldo
Commented Nov 9, 2023 at 7:58
• OK, great. Thanks! Commented Nov 9, 2023 at 8:00

using either "Extract[]"

to use Extract, you need to give Position

pred[{x_,y_,z_}] := x^2+y^2+z^2<=1;
d = 0.1;
v = Table[{x, y, z}, {x, -1, 1, d}, {y, -1, 1, d}, {z, -1, 1, d}] // Flatten[#,2]&;
v // Extract[v // Position[_?pred]] // Length


4169

Alternative view:

(pts = CoordinateBoundsArray[{{-1, 1}, {-1, 1}, {-1, 1}},
0.1]) // Dimensions

(ptsInside =
Select[Flatten[pts, 2], RegionMember[Ball[]]]) // Dimensions

Show[ListPointPlot3D[ptsInside, BoxRatios -> Automatic]
, Graphics3D[{
Opacity[0.3, Yellow], Ball[]
}]
]


using either "Select[]"

step by step

select all elements {x,y,z} satisfy the condition x^2+y^2+z^2≤1?

pred[{x_,y_,z_}] := x^2+y^2+z^2<=1;


then we need to make the list {p1, p2, ...}, so //Flatten[#,2]&;

which gives

pred[{x_,y_,z_}] := x^2+y^2+z^2<=1;
d = 0.1;
v = Table[{x, y, z}, {x, -1, 1, d}, {y, -1, 1, d}, {z, -1, 1, d}] // Flatten[#,2]&;
v // Select[pred] // Length


4169