5
$\begingroup$

$c$ is a vector with real numbers.I want to separate the positive ones and the negative ones into two vectors: $a$ and $b$.

I have the following problem: When I do:

c = RandomReal[{-1, 1}, 20];
{a, b} = GatherBy[c, Positive]

Sometimes, $a$ is the one with positive numbers, and some other times $b$ is the one with the positive numbers. Any solution to this problematic randomness?

$\endgroup$
0
5
$\begingroup$

The origin of your problem is that GatherBy gathers your data differently depending on the sign of the first number in list $c$.

You can avoid the problem by sorting the vector of real numbers $c$ before applying GatherBy, so that the $a$ list will always contain negative numbers:

c = Sort[RandomReal[{-1, 1}, 20]];
{a, b} = GatherBy[c, Positive]
$\endgroup$
2
  • $\begingroup$ Try it with c = Sort[{-2, -2}]; $\endgroup$ – Dr. belisarius Mar 7 '13 at 12:47
  • $\begingroup$ @belisarius Yep, in this form it works only under the assumption that the list c contains both positive and negative numbers. $\endgroup$ – VLC Mar 7 '13 at 13:47
4
$\begingroup$

Here's another way that removes the need to sort. Either

 {a, b} = {Select[c, # > 0 &], Select[c, # <= 0 &]}

or

 {a, b} = {Select[c, Positive], Select[c, Negative]}

which do the same thing except for any zero values.

$\endgroup$
4
$\begingroup$

Few more alternatives:

c = RandomReal[{-1, 1}, 10]
(* {-0.672076, -0.572152, -0.298228, -0.386248, 0.604312, -0.185637,
   0.983919, -0.926872, 0.479745, 0.407436} *)
{a, b} = Pick[c, Sign@c, #] & /@ {-1, 1} (* or *)
{a, b} = Cases[c, #] & /@ {_?NonPositive, _?Positive} (* or *)
{a, b} = DeleteCases[c, #] & /@ {_?Positive, _?NonPositive} (* or *)
{a, b} = Reap[If[# < 0, Sow[#, neg], Sow[#, pos]] & /@ c, {neg, pos}][[2]]
(* {{-0.672076, -0.572152, -0.298228, -0.386248, -0.185637, -0.926872},
    {0.604312, 0.983919, 0.479745, 0.407436}}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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