7
$\begingroup$

c and z are equal-sized lists. Whichever elements in z meet a certain criterion, I want a list of the corresponding elements from c. This is the clunky way I came up with:

c = RandomComplex[{-1 - I, 1 + I}, 20];
z = Abs[(((c^2 + c)^2 + c)^2 + c)^2 + c];
keepc = {};
Do[
  If[z[[k]] <= 2, AppendTo[keepc, c[[k]]]], {k, 1, Length[c]}];
keepc

What would be the proper way?

$\endgroup$

4 Answers 4

7
$\begingroup$
res = Extract[c, Position[z, x_ /; x <= 2]]

{-0.50405 + 0.330151 I, -0.368681 - 0.326179 I, -0.522155 - 0.224775 I, -0.699138 + 0.648737 I, 0.290045 - 0.242275 I, 0.0816587 - 0.519248 I, -0.695207 + 0.130671 I, -0.561304 - 0.323975 I, 0.334523 + 0.352494 I, 0.3687 - 0.502679 I}

res == keepc

(* True *)

Or, the other way around,

MapAt[Nothing, c, Position[z, x_ /; x > 2]] == keepc

(* True *)

Also:

res = Select[c, Abs[(((#^2 + #)^2 + #)^2 + #)^2 + #] <= 2 &]

res == keepc

(* True *)

And, with the same result,

z = Abs[(((x^2 + x)^2 + x)^2 + x)^2 + x];

c /. x_ /; Evaluate[z > 2] :> Nothing
$\endgroup$
1
  • $\begingroup$ Success! Thank you! Goodness, Matlab has me spoiled with its simple syntax. Too bad it does so little compared to Mathematica. $\endgroup$ Oct 1 at 22:12
6
$\begingroup$
Pick[c, UnitStep[2 - z], 1] == keepc
True

Also

c[[PositionIndex[UnitStep[2 - z]] @ 1]] == keepc

True

$\endgroup$
2
$\begingroup$

Using Sow/Reap:

Clear["Global`*"];
SeedRandom[1];
c = RandomComplex[{-1 - I, 1 + I}, 20];
z = Abs[(((c^2 + c)^2 + c)^2 + c)^2 + c];

Scan[If[Last@# <= 2, Sow[First@#]] &, Transpose[{c, z}]] // Reap // 
  Last // First

{-0.624394 + 0.424024 I, -0.517278 - 0.218836 I, 0.0844932 - 0.349297 I, -0.537691 + 0.18652 I, -0.207988 + 0.0375483 I, 0.400948 - 0.661974 I, -0.576348 - 0.0548697 I, -0.154299 - 0.976329 I, -0.50501 - 0.366248 I, 0.156112 - 0.0821956 I, -0.414261 - 0.0823102 I, -0.583898 + 0.455034 I}

Append is a slow operation and it is always preferable to Sow/Reap instead.

$\endgroup$
1
  • $\begingroup$ Ooooooh yeah, even not knowing the complete answer, I should have thought of using Sow/Reap. Thanks. I think you meant to say that Sow/Reap is preferable to Append. $\endgroup$ Oct 2 at 23:39
1
$\begingroup$

Using Query and Select:

c = RandomComplex[{-1 - I, 1 + I}, 20];
z = Abs[(((c^2 + c)^2 + c)^2 + c)^2 + c];
keepc = Query[Select[#[[2]] <= 2 &], First]@Transpose[{c, z}];
res = Extract[c, Position[z, x_ /; x <= 2]];

keepc === res

(*True*)
$\endgroup$

Your Answer

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

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