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 wish to use Distribute[p.(q+r)+m] to get p.q+p.r+m. However, Distribute apparently does not thread through all parts of the expression. What should I do instead?

share|improve this question
3  
Is Distribute[#] & /@ (p.(q + r) + m) acceptable ? –  b.gatessucks Nov 29 '12 at 9:26
    
@b.gatessucks This is not good because if there is a function like Log[a+b] inside the expression, the distribute would expand that too, yielding Log[a]+Log[b]. –  QuantumDot Jan 8 '13 at 20:06
    
@QuantumDot That would be a different question, too. –  b.gatessucks Jan 8 '13 at 20:10
    
Oh, that's true. On second thought, never mind. –  QuantumDot Jan 8 '13 at 20:24
add comment

3 Answers

You don't give a lot of context about how the target expression is generated (interactively or via code). The documentation for Distribute indicates that it won't automatically map down through an expression. But, one way to do this comes to mind.

Via code, using ReplaceAll and a replacement rule:

expr=p.(q+r)+m
expr /. d : HoldPattern[Dot[_, Plus[_, _]]] :> Distribute[d]
(* m + p.q + p.r *)
share|improve this answer
add comment

You could also define special symbols that distribute themselves when they get combined with Plus under a Dot operation. Here I denote those symbols with a hat:

Clear[OverHat];
OverHat /: Dot[x___OverHat, Plus[y__OverHat], z___OverHat] := 
 Plus @@ Thread[Dot[x, {y}, z]]

Then you can enter your expression like this:

OverHat[m] + OverHat[p].(OverHat[q] + OverHat[r])

where the OverHat is more easily input using the shortcut Ctrl7+^ to get this:

overhat

share|improve this answer
add comment
  p.(q + r) + m /. Dot -> Composition[Distribute, Dot]
  (* m + p.q + p.r *)

  Log[p.(q + Log[r + s])] + Log[a + b] + m /.  Dot -> Composition[Distribute, Dot]
  (* m + Log[a + b] + Log[p.q + p.Log[r + s]] *)
share|improve this answer
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.