3
$\begingroup$

This question already has an answer here:

I have a list with some values and I want to replace a value which is greater than 1 with 1 otherwise keep the value. In this case 10562:

   list[[1]]= {0.61975, 10562., 0.43274, 0.15068, 0.13703, 0.057564}

I tried this approach:

Table[If[list[[1, x]] > 1, list[[1, x]] = 1, list[[1, x]]], {x,
   1, Length[list[[1]]]}]

It works, but I'm wondering if there is a much simpler solution with mathematica. Can anybody help me out?

$\endgroup$

marked as duplicate by Mr.Wizard Feb 2 '14 at 7:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

12
$\begingroup$

Use Clip:

Clip[{0.61975, 10562., 0.43274, 0.15068, 0.13703, 0.057564}, {-Infinity, 1}]

{0.61975, 1, 0.43274, 0.15068, 0.13703, 0.057564}

$\endgroup$
  • 1
    $\begingroup$ @kirma A nice solution. Interesting that it does not work with Nothing. Say, if the task would be to remove all items exceeding 1 I am tempted to use the following: Clip[{0.61975, 10562., 0.43274, 0.15068, 0.13703, 0.057564}, {-Infinity, 1}, {Nothing, Nothing}]. This dowes not work though. $\endgroup$ – Alexei Boulbitch Mar 31 '17 at 6:40
2
$\begingroup$
{0.61975, 10562., 0.43274, 0.15068, 0.13703, 0.057564} /.x_ /; x >= 1 -> 1
(*  {0.61975, 1, 0.43274, 0.15068, 0.13703, 0.057564}  *)
$\endgroup$
  • $\begingroup$ There's definitely more than one way to do it in Mathematica. :-| $\endgroup$ – kirma Jan 31 '14 at 15:46
  • 1
    $\begingroup$ @kirma Clip will perform much better than this replacement rule; you chose the best one I know of. $\endgroup$ – Mr.Wizard Jan 31 '14 at 15:48
  • 1
    $\begingroup$ @krima Clip is, of course, better, since it is a function specially designed for purposes of such a sort. I believe, however, that it is useful to have several solutions, even if they are not as good. Further, what is better and what is worse depends upon the point of view. People usually think that the good==fast. However, we often deal with problems in which the timing of application one approach imperceptibly differs from another. $\endgroup$ – Alexei Boulbitch Feb 3 '14 at 8:54
  • $\begingroup$ @krima, continuation: In this case the best solution is the first coming to mind, provided it gives an answer in the matter of a second, since in this case it is the looking for solution that is the time-limiting step. Anyway, I like your solution more than mine. $\endgroup$ – Alexei Boulbitch Feb 3 '14 at 8:55

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