applying If then function to a list of lists..

I would like to recode a list of random numbers in the form of {{r1,r2,r3},{r4,r5,r6}} (The array could be much larger) by replacing each random number by a value MAX if the random variable was greater than MAX

So If[x<MAX,x,MAX]

So if r1 and r3 were greater than MAX then my list would be recoded to {{MAX,r2,MAX},{r4,r5,r6}}

This should be straightforward but for some reason I can’t seem to find it straightforward :slight_smile:

In[1]:= MAX = .5;
m = RandomReal[{0, 1}, {3, 3}]

Out[2]= {
  {0.7511, 0.0403175, 0.356029},
  {0.0846003, 0.417139, 0.894121},
  {0.670992, 0.181403, 0.755288}}

In[3]:= n = m /. v_?NumericQ -> If[v < MAX, v, MAX]

Out[3]= {
  {0.5, 0.0403175, 0.356029},
  {0.0846003, 0.417139, 0.5},
  {0.5, 0.181403, 0.5}}

In[4]:= f[v_] := If[v < MAX, v, MAX];
n = Map[f, m, {-1}]

Out[5]= {
  {0.5, 0.0403175, 0.356029},
  {0.0846003, 0.417139, 0.5},
  {0.5, 0.181403, 0.5}}

There is also Clip:

In[2]:= Clip[m, {-Infinity, 0.5}]
Out[2]= {{0.5, 0.0403175, 0.356029}, {0.0846003, 0.417139, 0.5}, {0.5, 0.181403, 0.5}}

Bill, Thank you for your reply

n = Map[f, m, {-1}]

Can you point me to where the {-1} argument is described as I can’t seem to find it. I can find the +ve ones but not the -ve ones

If you think of your expression as the root of a tree, with 1 being at ground level, 2 being one level deeper, 3 being one level even deeper

then negative levels start at the very bottom tips of the roots and count upwards, so -1 is the very bottom, -2 is one level higher, etc.

This
http://reference.wolfram.com/mathematica/tutorial/LevelsInExpressions.html

briefly mentions negative levels near the bottom of that page.

My purpose in using the {-1} was to restrict the matching to the individual numers and avoid matching rows or even the whole matrix.

Thanks Bill most helpful I am impressed.

Illian Clip is great another function in mathematica I hadn’t come across.!