4
$\begingroup$

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.

$\endgroup$

4 Answers 4

4
$\begingroup$
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

To answer the comment:

flat = Flatten[res, 1]

(* outputs 4169 triples *)

Addendum

As a oneliner with the desired flatness:

Cases[#, {__Real}, -1] & @
 ReplaceAll[{a_, b_, c_} /; a^2 + b^2 + c^2 > 1 :> Nothing] @ v
$\endgroup$
5
  • $\begingroup$ 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? $\endgroup$ Nov 9, 2023 at 7:48
  • $\begingroup$ Please see updated answer $\endgroup$
    – eldo
    Nov 9, 2023 at 7:52
  • $\begingroup$ 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 ":>"? $\endgroup$ Nov 9, 2023 at 7:53
  • $\begingroup$ a_Real wasn't necessary, so I deleted it (good observation). :> stands for RuleDelayed (see Documentation) $\endgroup$
    – eldo
    Nov 9, 2023 at 7:58
  • $\begingroup$ OK, great. Thanks! $\endgroup$ Nov 9, 2023 at 8:00
4
$\begingroup$

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

$\endgroup$
3
$\begingroup$

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[]
   }]
 ]

enter image description here

$\endgroup$
2
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.