I have a list of reals and I'm replacing those which are contained in a given interval with two different values depending on wheter the selected reals are positive or negative.
I came up with this (overly convoluted) code:
list = {-2., -1.6, -1.2, -0.8, -0.4, 0., 0.4, 0.8, 1.2, 1.6, 2.}
list /. MapThread[#2 -> #1 &, {If[TrueQ[#], 1, -1] & /@ Positive /@ #, #}]&@Cases[list, x_ /; -1 < x < 1]
This does the work, but I'm sure there are more efficent ways of dealing with replacing elements of a list according to multiple criteria.
My question is how could I make a better use of pattern matching to solve the problem and thus possibly shorten/simplify the code.
Edit:
Generalizing the problem, given a list of numbers, I need to:
1. Identify all the numbers between a choosen interval
2. Check which of these numbers are positive and which are negative
3. Replace each of them with one of the two new choosen values, according to their sign
Here's another example with my old code:
list = {-3., -2.6, -2.2, -1.8, -1.4, -1., -0.6, -0.2, 0.2, 0.6, 1., 1.4, 1.8, 2.2, 2.6`, 3.}
{min, max} = {-1.5, 3};
{newValueIfPositive, newValueIfNegative} = {50, 700};
list /. MapThread[#2 -> #1 &, {If[TrueQ[#], newValueIfPositive,newValueIfNegative] & /@ Positive /@ #, #}] &@Cases[list, x_ /; min < x < max]
{-2., -1.6, -1.2, -0.8, -0.4, 0., 0.4, 0.8, 1.2, 1.6, 2.} /. x_ /; Abs[x] < 1 :> (1 - 2 UnitStep[-x])
? $\endgroup$list /. {x_ /; -1 < x <= 0 -> -1, x_ /; 0 < x < 1 -> 1}
$\endgroup$Block[{b = UnitBox[list/2]}, list + b (Sign[list] + list)]
a bit slower than @SimonWoods ' answer $\endgroup$list /. x_ /; min < x < max :> Rescale[Sign[x], {-1, 1}, {700, 50}]
. But did you think about how to handle 0? $\endgroup$