6
$\begingroup$

I have a list

list={-1,0,1,2,3};

I wish to multiply any element greater than 0.5 by a constant, say 5.0 so that I wind up with

list = {-1,0,5,10,15}

without using a Do loop.

I'm hoping it is crazy simple.

Thanks again in advance.

$\endgroup$
  • 2
    $\begingroup$ If[# > .5, 5 #, #] & /@ list? $\endgroup$ – kglr Apr 25 '17 at 1:22
  • $\begingroup$ Dang, that does it nicely. I'm starting to get the feel for the & /@ construct. $\endgroup$ – Tom Mozdzen Apr 25 '17 at 1:30
  • 2
    $\begingroup$ @TomMozdzen Those are two separate constructions: the ...#...& notation for anonymous functions, and /@ for map. You could use one or the other, or neither as in tom[x_]:=If[x>.5,5x,x];Map[tom,list] $\endgroup$ – Mark S. Apr 25 '17 at 2:12
  • 1
    $\begingroup$ If you're not yet comfortable with slots (# +&): Function[x, If[x > .5, 5 x, x]] /@ list. $\endgroup$ – J. M. will be back soon Apr 25 '17 at 3:35
6
$\begingroup$
(1 - UnitStep[# - .5]) # + 5 UnitStep[# - .5] # &@list

or

 # (5 UnitStep[# - .5] /. 0 -> 1) &@list

or

If[# > .5, 5 #, #] & /@ list

{-1, 0, 5, 10, 15}

$\endgroup$
  • $\begingroup$ I like the 3rd one the best, but the 1st two also offer alternative methods. Sure wish there was an example page with a ton of these to get this syntax down pat. $\endgroup$ – Tom Mozdzen Apr 25 '17 at 1:47
6
$\begingroup$

Using Replace with a level spec works as well:

Replace[list, n_ /; 0.5 < n :> 5*n, {1}]
(* {-1, 0, 5, 10, 15} *)

Here, {1} means that you try to replace each expression at level $1$ (and only level $1$) for replacement, and :> is syntactic sugar for RuleDelayed, which means the right hand side (5 * n) is only evaluated after the pattern on the left hand side (n_ /; 0.5) matches, and is evaluated each time it matches.

$\endgroup$
  • $\begingroup$ Ah - got it, but the condition should be n > 0.5. Also, could you please explain what the {1} does and what the :> does? is the :> an assignment? $\endgroup$ – Tom Mozdzen Apr 25 '17 at 1:40
  • 2
    $\begingroup$ Shorter version... list /. (i_ /; i > 0.5 :> 5 i) (ie, harder to read...) $\endgroup$ – kale Apr 25 '17 at 3:07
2
$\begingroup$
Function[x, If[x > 0.5, 5 x, x], Listable][list]
(* {-1, 0, 5, 10, 15} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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