1
$\begingroup$

Is there a tidy way to create a list of the indices of elements of a list that meet specified conditions?

This method gets the job done, but it's clumsy and not conducive to nesting:

x = RandomReal[1, 100];
t = {};
Do[If[x[[i]] < .2, t = Join[t, {i}]], {i, Length[x]}];
t

(* {13, 24, 31, 32, 44, 45, 46, 49, 50, 51, 52, 54, 57, 65, 70, 75, 76, 81, 87, 97} *)

Position almost does what I want, but it annoyingly returns a list of lists instead of a list of indices:

Position[x, _?(# < .2 &)]

(* {{5}, {14}, {16}, {19}, {22}, {24}, {28}, {42}, {43}, {45}, {50}, \ {51}, {54}, {58}, {63}, {72}, {86}, {91}, {98}} *)

This prevents me from being able to use the output of Position as a list of indices. So this fails:

x = RandomReal[1,100];
y = RandomReal[1,Length[x]];
tt = Position[x, _?(# < .2 &)];
y[[tt]]

I am also kind of curious, WHY does MMa so often give results in that irritating "list of lists" format above?

$\endgroup$
8
  • 3
    $\begingroup$ Hi, take a look at Position's documentation page. Position[x, _?(# < .2 &)]. $\endgroup$
    – Kuba
    Feb 3, 2015 at 20:40
  • $\begingroup$ @Kuba, Thanks. That almost works, but it returns a list with each index as a list: {{5}, {14}, {16}, {19}}. I need just a list of indices. $\endgroup$ Feb 4, 2015 at 0:19
  • $\begingroup$ @JerryGuern "Position returns a list of positions in a form suitable for use in Extract, ReplacePart, and MapAt." [Docs.] $\endgroup$
    – Michael E2
    Feb 4, 2015 at 1:53
  • 1
    $\begingroup$ This should be considerably faster than Position: SparseArray[UnitStep[x - 0.2], Automatic, 1]["AdjacencyLists"]. More examples found within: mathematica.stackexchange.com/search?q=SparseArray+UnitStep $\endgroup$
    – Mr.Wizard
    Feb 4, 2015 at 8:00
  • $\begingroup$ @MichaelE2 I'm not clear on why this was closed as off-topic. Granted, if could have found the answer the Position documentation, IF I had known that Position was the answer I was looking for. $\endgroup$ Feb 20, 2015 at 23:58

1 Answer 1

0
$\begingroup$

This can be done with Position and Flatten. Thanks for the help, Kuba.

tt = Flatten[Position[x, _?(# < .2 &)]]
$\endgroup$

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