Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    
HoldForm[1-x](a+b) // Expand? –  J. M. Oct 30 '12 at 11:17
    
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)? –  janitor048 Oct 30 '12 at 11:27
    
Again, look up HoldForm[]. And while you're at it, Defer[] too. –  J. M. Oct 30 '12 at 11:28
add comment

2 Answers

up vote 7 down vote accepted

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

share|improve this answer
    
provided you remember to do Expand afterwards ;-) –  chris Oct 30 '12 at 12:06
    
Thanks, I didn't think of substituting the (1-x) term with its HoldForm variant.. –  janitor048 Oct 30 '12 at 16:04
add comment

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.

share|improve this answer
2  
...and by using a formal variable like \[FormalU], one could skip the use of Module[] in expandExcept[]... –  J. M. Oct 30 '12 at 22:35
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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