# Replacing constant factors

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.)

• See this. It will explain how to write such a pattern. – b3m2a1 Sep 2 '17 at 23:10
• The solution I came up with now is expr //. {x^p_ -> x^p, Subscript[i_, j_] -> Subscript[i, j], n_Integer -> 2*n} Improvement allowed. I have installed Mathematica for 6 hours now and I am just starting to learn. Thanks – Page not found Sep 3 '17 at 0:38
• What do you want done with an implied constant of 1? Should x become  2 x? – Bob Hanlon Sep 3 '17 at 13:03
• Side note: Since you're just starting, you might be interested in point 3 here among others. Also this answer might be relevant, too. – Michael E2 Sep 3 '17 at 15:55
• Hi, welcome to Mathematica.SE, Thanks for taking the tour. Once you gain enough reputation by making good questions you will be able to vote up and down both questions and answers. Your question has been answered, and there are things to do after that. Its good practice to wait 24hours for other answers before up-voting and accepting the best one for you. – rhermans Sep 9 '17 at 13:28

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, ##]

Replace[expr, {d_ x^p_ -> 2 d  x^p,
a_  Subscript[exp___] -> 2 a Subscript[exp]}, All]


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