Cases
, Select
,Pick
and Position
each have different syntaxes and purposes, but there are times when you can express the same calculation equivalently using either of them. So with this input:
test = RandomInteger[{-25, 25}, {20, 2}]
{{-15, 13}, {-8, 16}, {-8, -19}, {7, 6}, {-21, 9}, {-3, -25}, {21, -18}, {4, 4}, {2, -2}, {-24, 8}, {-17, -8}, {4, -18}, {22, -24}, {-4, -3}, {21, 0}, {19, 18}, {-23, -8}, {23, -25}, {14, -2}, {-1, -13}}
You can get the following equivalent results:
Cases[test, {_, _?Positive}]
{{-15, 13}, {-8, 16}, {7, 6}, {-21, 9}, {4, 4}, {-24, 8}, {19, 18}}
Select[test, #[[2]] > 0 &]
{{-15, 13}, {-8, 16}, {7, 6}, {-21, 9}, {4, 4}, {-24, 8}, {19, 18}}
Pick[test, Sign[test[[All, 2]] ], 1]
{{-15, 13}, {-8, 16}, {7, 6}, {-21, 9}, {4, 4}, {-24, 8}, {19, 18}}
test[[Flatten@Position[test[[All, 2]], _?Positive] ]]
{{-15, 13}, {-8, 16}, {7, 6}, {-21, 9}, {4, 4}, {-24, 8}, {19, 18}}
Are there performance or other considerations that should guide which you should use? For example, is the pattern-matching used in Cases
likely to be slower than the functional tests used in Select
? Are there any generic rules of thumb, or is testing the particular case you are using the only solution?
Extract[test, Position[test[[All, 2]], _?Positive]]
Note its near identity, but for the bracketing of the list of positions, withPart[test, Flatten[Position[test[[All, 2]], _?Positive]]]
$\endgroup$