2

Goal: I want to multiply all constant factors in an expression by 2. For example,

4 x^2 (4 Subscript[a, 1] + Subscript[a, 2] - 7 Subscript[c, 4])

should be transformed to

8 x^2 (8 Subscript[a, 1] + Subscript[a, 2] - 14 Subscript[c, 4])

However, I don't want the replacement to apply for powers (such as x^2) and subscripts.

On my attempt to explicitly name the expressions that should be changed (which would be too much work anyway because it's not a generic solution) replacement also affects power and subscripts:

4 x^2 (4 Subscript[a, 1] + Subscript[a, 2] - 7 Subscript[c, 4]) /. 2 -> 4 (* wrong *)

(A solutions that turns Subscript[a, 2] in 2 Subscript[a, 2] would also be fine.)

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574

3 Answers3

1
Replace[expr, {d_ x^p_ -> 2 d  x^p, 
  a_  Subscript[exp___] -> 2 a Subscript[exp]}, All]
jiaoeyushushu
  • 911
  • 6
  • 10
1

Instead of "protecting" some kinds of expressions, you could just explicitly specify that you only want to replace products with integers:

Replace[
  4 x^2 (4 Subscript[a, 1] + Subscript[a, 2] - 7 Subscript[c, 4]),
  n_Integer a_ :> 2 n a,
  All
]

This way, you don't risk forgetting to protect some form of expression

Lukas Lang
  • 33,963
  • 1
  • 51
  • 97
1

You can replace the explicit Times operator with one that doubles:

expr = 4 x^2 (4 Subscript[a, 1] + Subscript[a, 2] - 7 Subscript[c, 4]);

expr /. Times :> (2 ## &)
8 x^2 (8 Subscript[a, 1] + Subscript[a, 2] - 14 Subscript[c, 4])

## is shorthand for SlotSequence[], and 2 ## is Times[2, ##]

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371