14

I began to use Mathematica a few days ago. My problem is: how do I expand expressions like $(a+b)\ast(a+b)$, where the multiplication is noncommutative? Can Mathematica do this?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
jon jones
  • 465
  • 3
  • 10

2 Answers2

13

Distribute[] is a useful thing:

Distribute[(a + b) ** (c + d)]
   a ** c + a ** d + b ** c + b ** d
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
  • 2
    Although this works on the example used by jon, it doesn't really answer the question satisfactorily (although the question was vague). For instance, it does not work on Distribute[a.(c + d)/2]. – Jess Riedel Feb 29 '20 at 13:55
  • @Jess, yes, that case is a little problematic.OTOH, a rearrangement of that expression, along with using the second and third arguments of Distribute[] succeeds: Distribute[(a/2).(c + d), Plus, Dot] – J. M.'s missing motivation Mar 02 '20 at 05:38
  • 2
    I mean, ok, but the whole point of this is to avoid re-arranging the expressions by hand, because the cases when you really want to use this are when you have 30 terms. – Jess Riedel Mar 02 '20 at 11:32
  • It doesn't work for expression with sum. For example Distribute[(a + b) ** (c + d) + a ** (b + d)] – dtn May 19 '22 at 04:18
  • 1
    @dtn, indeed, so one has to use /. in such cases, e.g. (a + b) ** (c + d) + a ** (b + d) /. nc_NonCommutativeMultiply :> Distribute[nc]. – J. M.'s missing motivation May 19 '22 at 12:04
  • @J.M. is it possible to do the reverse assembly operation? – dtn May 20 '22 at 04:27
  • @dtn, sounds like that could be a new question. – J. M.'s missing motivation May 20 '22 at 13:10
  • @J.M. let's try https://mathematica.stackexchange.com/questions/268454/noncommutative-multiply-expand-expression-and-then-assembly-back – dtn May 20 '22 at 13:21
6

The package NCAlgebra does exactly what you want.

NCExpand[(a + b) ** (a + b)]
(* a ** a + a ** b + b ** a + b ** b *)
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
Mauricio de Oliveira
  • 2,001
  • 13
  • 15