6
$\begingroup$

That's must be a very trivial question. Suppose we have the simple list

data = {{-1, 0}, {0.2, 0.4}, {4, 0}, {0.3, 0}, {0.2, -0.4}};

Then, is there a quick and elegant way to pick the element with non-zero and positive y value? In this example, we should get {0.2, 0.4}.

$\endgroup$
3
  • 4
    $\begingroup$ Select[data, Positive[#[[2]]]&] $\endgroup$
    – Jason B.
    Jun 27, 2019 at 14:36
  • $\begingroup$ Alternatively, data//Pick[#, Sign[#[[All,2]]],1]& $\endgroup$
    – user1066
    Jun 27, 2019 at 15:50
  • $\begingroup$ A minor variation: Select[Positive@*Last][data] $\endgroup$
    – Syed
    Feb 4 at 2:07

6 Answers 6

5
$\begingroup$

Select is a good option here. Jason has shown in the comments how to use the Positive function. If you want a bit more flexibility for future usage, you can use a standard greater than operator.

data = {{-1, 0}, {0.2, 0.4}, {4, 0}, {0.3, 0}, {0.2, -0.4}};    
positivedata=Select[data, #[[2]] > 0 &]
$\endgroup$
4
$\begingroup$

You can also use Cases:

Cases[{_, _?Positive}] @ data

{{0.2, 0.4}}

$\endgroup$
2
$\begingroup$
data = {{-1, 0}, {0.2, 0.4}, {4, 0}, {0.3, 0}, {0.2, -0.4}};

Pre-define pattern for better comparability

p = {_, x_} /; x <= 0;

Using SequenceSplit (new in 11.3)

First @ SequenceSplit[data, {p}]

{{0.2, 0.4}}

Using ReplaceAt (new in 13.1)

ReplaceAt[data, _ :> Nothing, Position[p] @ data]

{{0.2, 0.4}}

Using ReplaceAll

data /. p :> Nothing

{{0.2, 0.4}}

Using Delete

Delete[Position[p] @ data] @ data

{{0.2, 0.4}}

$\endgroup$
1
$\begingroup$
data = {{-1, 0}, {0.2, 0.4}, {4, 0}, {0.3, 0}, {0.2, -0.4}, {-1, -1}};

Using Pick:

Pick[#, Element[#, PositiveReals] & /@ #] &@data

(*{{0.2, 0.4}}*)

Or using DeleteCases:

DeleteCases[data, s_ /; ! MatchQ[Sign@s, {1 ..}]]

(*{{0.2, 0.4}}*)

An alternative using Pick:

Pick[#, MatchQ[Thread[{##} > 0], {True ..}] & @@@ #] &@data

(*{{0.2, 0.4}}*)
$\endgroup$
2
  • 1
    $\begingroup$ I know it works for this case but if data have {-1,-1}, then your approach will not work. $\endgroup$ Feb 4 at 1:07
  • $\begingroup$ Thanks for the observation, @OkkesDulgerci! See the update, please. :-) $\endgroup$ Feb 4 at 1:18
1
$\begingroup$

A Reap/Sow variant:

Reap[Sow @@@ data, _?(# > 0 &), {#2[[1]], #1} &][[2]]
$\endgroup$
1
$\begingroup$
data = {{-1, 0}, {0.2, 0.4}, {4, 0}, {0.3, 0}, {0.2, -0.4}};

Select[0 < ArcTan @@ # < π &][data]

{{0.2, 0.4}}


Visualization:

pts = RandomReal[{-1, 1}, {400, 2}];
sel = Select[0 < ArcTan @@ # < π &][pts];
unsel = Complement[pts, sel];
ListPlot[{sel, unsel}, PlotStyle -> {Red, Blue}]

enter image description here

$\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.