Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

$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?

share|improve this question
add comment

3 Answers

up vote 4 down vote accepted

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]
share|improve this answer
    
Try it with c = Sort[{-2, -2}]; –  belisarius Mar 7 '13 at 12:47
    
@belisarius Yep, in this form it works only under the assumption that the list c contains both positive and negative numbers. –  VLC Mar 7 '13 at 13:47
add comment

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.

share|improve this answer
add comment

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}}*)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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