I'd like to replace all values in a list which obey one or more criteria with another value.
Example: Replace all values>30
by $30$.
data={{3,35},{2,7}}
Afterwards it should be:
{{3,30},{2,7}}
Example #2:
aa= {300., 150., 100., 76.8421, 64.0909, 55.567, 49.1935, 44.2262,
40.2247, 36.9355, 34.1667, 31.8138, 29.7887, 28.0087, 26.4537,
25.0612, 23.8186, 22.7059, 21.6854, 20.7663, 19.9265, 19.1519,
18.4323, 17.7739, 17.1672, 16.6007, 16.0648, 15.5605, 15.098}
If a value of aa
is greater than 100 I want to replace it with an arbitrary value, e.g. 50.
Answer
Up front you have a choice between pattern-based and numeric manipulation of an array. Pattern-based is more general; numeric is usually fastest when applicable.
a = {{21, 95, 50}, {39, 32, 76}, {9, 12, 75}};
Examples of pattern based methods:
a /. n_Integer /; n > 30 -> 30
a /. n_?NumericQ /; n > 30 -> 30
Replace[a, n_?(#>30&) -> 30, {2}]
Examples of numeric methods:
Clip[a, {-∞, 30}]
(a - 30) UnitStep[30 - a] + 30
Other, less desirable methods:
If[# > 30, 30, #, #] & //@ a
Map[#~Min~30 &, a, {-1}]
Fast numeric methods for the second example:
Clip[aa, {-∞, 100}, {0, 50.}]
(1 - #) 50. + aa # & @ UnitStep[100 - aa]
Comments
Post a Comment