2
$\begingroup$

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

$\endgroup$
5
  • $\begingroup$ See this. It will explain how to write such a pattern. $\endgroup$
    – b3m2a1
    Sep 2, 2017 at 23:10
  • $\begingroup$ 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 $\endgroup$ Sep 3, 2017 at 0:38
  • 1
    $\begingroup$ What do you want done with an implied constant of 1? Should x become ` 2 x`? $\endgroup$
    – Bob Hanlon
    Sep 3, 2017 at 13:03
  • $\begingroup$ Side note: Since you're just starting, you might be interested in point 3 here among others. Also this answer might be relevant, too. $\endgroup$
    – Michael E2
    Sep 3, 2017 at 15:55
  • $\begingroup$ 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. $\endgroup$
    – rhermans
    Sep 9, 2017 at 13:28

3 Answers 3

1
$\begingroup$

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

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

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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