Is there a short method to select positive real numbers from a list containing both reals and complex numbers? Thank you!
Asked
Active
Viewed 6,342 times
8 Answers
12
My guess:
Select[list, Positive]
This is also quite efficient with larger lists...
Henrik Schumacher
- 106,770
- 7
- 179
- 309
6
list = {1, 11.2, -12, a, 10 + I};
Cases[list, s_ /; Im[s] == 0 && s > 0]
{1, 11.2}
Rom38
- 5,129
- 13
- 28
-
Thank you very much! I now my question is simple, but there is no simple method in Mathematica for these cases. I have been wondering why Mathematica doesn´t have a selection for this case like in the case of _Integer or sometimes ,Reals! I would like if the authors of Mathematica could introduce kind of Select [{ },_PositiveReals] option. Thank you again! – HdoMat Jul 03 '17 at 14:51
5
L = RandomSample[Join[RandomReal[{-2, 2}, 1000],
RandomComplex[{-2 - 2 I, 2 + 2 I}, 1000]]];
Pick[L, Positive[L]]
Coolwater
- 20,257
- 3
- 35
- 64
3
The question was to select positive real numbers, so it could be interpreted as
Select[list, Positive @ # && Head @ # === Real &]
{11.2}
eldo
- 67,911
- 5
- 60
- 168
1
list = {1, 11.2, -12, a, 10 + I};
If we treat 1 as as a real number, we can use PositiveReals (new in V 12.0):
Select[list, # \[Element] PositiveReals &]
{1, 11.2}
This is in line with RealValuedNumberQ (new in V 13.3):
RealValuedNumberQ /@ {1, 11.2}
{True, True}
Recommended Reading:
eldo
- 67,911
- 5
- 60
- 168
1
list = {1, 11.2, -12, a, 10 + I};
You can use DeleteCases as follows:
DeleteCases[list, x_ /; ! MatchQ[x, _?Positive]]
({1, 11.2})
Or using GroupBy and Lookup:
Lookup[GroupBy[list, Positive], True]
({1, 11.2})
E. Chan-López
- 23,117
- 3
- 21
- 44