4
$\begingroup$

I have a list

a = {1, 8, 0, 6, 5, 3, 5, 2, 2, 5}

I want to generate a new list whose elements are the same of a if it's bigger than 5, or 5 elsewhere. I managed to achieve this using Map and a pure function doing

Map[(Max[#, 5]) &, a]

but this looks a bit clumsy to me. Is there a better way?

EDIT: I found this solution

a /. x_ /; x < 5 -> 5

but I cannot really understand why is working. Could someone give an insight into it?

Thanks

$\endgroup$
  • 2
    $\begingroup$ Why not Max[#, 5] & /@ a ? $\endgroup$ – Mauro Lacy Jan 3 at 11:38
6
$\begingroup$

You can use Clip or Ramp:

Clip[a, {5, ∞}]

{5, 8, 5, 6, 5, 5, 5, 5, 5, 5}

5 + Ramp[a - 5]

{5, 8, 5, 6, 5, 5, 5, 5, 5, 5}

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.