6

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}.

Vaggelis_Z
  • 8,740
  • 6
  • 34
  • 79

6 Answers6

5

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 &]
kickert
  • 1,820
  • 8
  • 22
4

You can also use Cases:

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

{{0.2, 0.4}}

kglr
  • 394,356
  • 18
  • 477
  • 896
2
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}}

eldo
  • 67,911
  • 5
  • 60
  • 168
1
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}})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
1

A Reap/Sow variant:

Reap[Sow @@@ data, _?(# > 0 &), {#2[[1]], #1} &][[2]]
ubpdqn
  • 60,617
  • 3
  • 59
  • 148
1
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

Syed
  • 52,495
  • 4
  • 30
  • 85