1
$\begingroup$

So I have a list of data that contain both positive and negative values, and I am wondering what I have to do in order to make all the numbers positive.

$\endgroup$
  • 2
    $\begingroup$ You didn't say what relation those positive numbers should have to your original numbers, therefore the following is also a valid solution to the problem you stated: 1&/@yourlist — this just replaces all entries of your list with 1, which clearly is positive. $\endgroup$ – celtschk Oct 20 '12 at 7:42
  • $\begingroup$ Redefine Min[data]-1 as 0 ? $\endgroup$ – image_doctor Oct 20 '12 at 17:04
  • 1
    $\begingroup$ Unprotect[Positive]; Positive[_] := True; $\endgroup$ – Rojo Oct 20 '12 at 18:00
14
$\begingroup$

If you are indifferent to the way your data are made positive, then check Abs function out, which is defined as Abs[x] == x Sign[x]. It leaves zeros unchanged, but does make negative numbers positive. It then suffices to evaluate posdata = Abs[data].

$\endgroup$
3
$\begingroup$

Assuming the list contains negative numbers, you could shift everything to the right on the number line by adding the absolute value of the smallest number plus one. This would preserve the ordering of the elements in your list.

d = RandomInteger[{-10, 10}, 20];

{-2, -7, 10, 5, 5, 7, -3, 7, 2, -2, 9, -8, -1, 1, 3, -8, -6, 8, 0, 3}

d + (Abs@Min@d + 1)

{7, 2, 19, 14, 14, 16, 6, 16, 11, 7, 18, 1, 8, 10, 12, 1, 3, 17, 9, 12}

$\endgroup$
0
$\begingroup$
list = RandomInteger[{-10, 10}, 20]

{8, -2, -1, -1, 10, -10, -9, -4, -2, 3, -2, -1, -8, 1, 6, 5, 0, 3, 5, -10}

When you apply Abs[] to a list, it will be applied to each element of that list:

Abs[list]
Abs @ list

Both return

{8, 2, 1, 1, 10, 10, 9, 4, 2, 3, 2, 1, 8, 1, 6, 5, 0, 3, 5, 10}

Note: That also goes for other functions, like addition:

list + 100

doesn't add the number 100 at the end of the list, but adds 100 to each element:

{108, 98, 99, 99, 110, 90, 91, 96, 98, 103, 98, 99, 92, 101, 106, 105, 100, 103, 105, 90}

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