5
$\begingroup$

I've got an expression like

expr = (1-x)(a+b)

that I would like to distribute / expand while keeping factors of (1-x) intact, i.e. the result should in the above example should look like

(1-x)a + (1-x)b

I know that for the explicit example given here, Expand[expr,(a+b)] would yield the desired result. However, I would need a solution where (a+b) can be any arbitrary algebraic expressions that is distributed with (1-x) being left untouched.

Is there maybe a way to define a pattern that matches my (1-x) terms that I can than hold while distributing?

$\endgroup$
  • $\begingroup$ HoldForm[1-x](a+b) // Expand? $\endgroup$ – J. M. will be back soon Oct 30 '12 at 11:17
  • $\begingroup$ Yes, but for an already existing expression (that is somewhat more complicated than my example) - how do I tell Mathematica to hold all occurrences of (1-x)? $\endgroup$ – janitor048 Oct 30 '12 at 11:27
  • $\begingroup$ Again, look up HoldForm[]. And while you're at it, Defer[] too. $\endgroup$ – J. M. will be back soon Oct 30 '12 at 11:28
7
$\begingroup$

Does expr /. (1-x) -> HoldForm[1-x] work? That should Hold all occurences of (1-x) in your expression.

$\endgroup$
  • $\begingroup$ provided you remember to do Expand afterwards ;-) $\endgroup$ – chris Oct 30 '12 at 12:06
  • $\begingroup$ Thanks, I didn't think of substituting the (1-x) term with its HoldForm variant.. $\endgroup$ – janitor048 Oct 30 '12 at 16:04
6
$\begingroup$

We could substitute a variable for the expression we wish to preserve, expand the result, and then substitute the expression back for the variable. Like so:

expandExcept[expr_, exception_] :=
  Module[{u}, Expand[expr /. exception -> u] /. u -> exception]

expandExcept[(1-x)(a+b), 1-x]
(* a (1-x) + b (1-x) *)

expandExcept[(1-x)/(a+b)+(1-x)^2(c+d)^3, 1-x]
(* (1-x)/(a+b) + c^3 (1-x)^2 + 3 c^2 d (1-x)^2 + 3 c d^2 (1-x)^2 + d^3 (1-x)^2 *)

This has the advantage over a solution based upon HoldForm in that the result remains a valid algebraic expression.

$\endgroup$
  • 2
    $\begingroup$ ...and by using a formal variable like \[FormalU], one could skip the use of Module[] in expandExcept[]... $\endgroup$ – J. M. will be back soon Oct 30 '12 at 22:35

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.