Tell me more ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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}}

share|improve this question
4  
data /. x_ /; x > 30 -> 30 ? – b.gatessucks Aug 22 '12 at 13:19
2  
Only for the one criterium: Clip[{{3, 35}, {2, 7}}, {-Infinity, 30}] – Yves Klett Aug 22 '12 at 13:26
2  
...or data /. x_ -> Min[x, 30]. – J. M. Aug 22 '12 at 13:26
6  
With all due respect to all involved, why answering in comments? The question is (IMO) borderline RTFM, which is probably why people used comments. But it would IMO be better if one either decides to answer and puts an answer or decides to close and puts a close vote. Comments are generally not intended to replace answers. – Leonid Shifrin Aug 22 '12 at 13:59
1  
@LeonidShifrin I agree. I've voted to close as TL now, but the OP is welcome to use the comments above to write an answer with the different approaches with explanations. It might also be a good learning experience for them (cc: rainer) – rm -rf Aug 22 '12 at 16:31
show 7 more comments

1 Answer

up vote 1 down vote accepted

I couldn't find a question that is an exact duplicate of this one.

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}]
share|improve this answer
Holy <unprintable>! When did you hit 30k? Congrats! – rcollyer Aug 24 '12 at 15:28
@rcollyer lol -- a couple of days ago. Thanks. :-) – Mr.Wizard Aug 24 '12 at 15:29
Well, that serves me right for not paying attention. – rcollyer Aug 24 '12 at 15:29

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.