7
$\begingroup$

I want to define a function in Mathematica where I get all combinations of an expression, e.g., input:

{q,p1,p2}

Output:

{q + p1 + p2, q + p1 - p2, q - p1 + p2, -q + p1 + p2, -q - p1 + p2, -q + p1 - p2, -q - p1 - p2}

I am only interested in Plus/Minus.

I really need your help guys.

$\endgroup$
14
$\begingroup$

Tuples + Dot:

Tuples[{1, -1}, 3].{q, p1, p2}

{p1 + p2 + q, p1 - p2 + q, -p1 + p2 + q, -p1 - p2 + q, p1 + p2 - q, p1 - p2 - q, -p1 + p2 - q, -p1 - p2 - q}

For arbitrary number of variables:

ClearAll[f]
f[n_] := Tuples[{1, -1}, n].Array[Subscript[q, #] &, n]

f[3] // TeXForm

$\scriptsize\left\{q_1+q_2+q_3,q_1+q_2-q_3,q_1-q_2+q_3,q_1-q_2-q_3,-q_1+q_2+q_3,-q_1+q_2-q_3,-q_1-q_2+q_3,-q_1-q_2-q_3\right\}$

Also

Flatten @ Outer[{q, p1, p2}.{##} &, {1, -1}, {1, -1}, {1, -1}]

{p1 + p2 + q, p1 - p2 + q, -p1 + p2 + q, -p1 - p2 + q, p1 + p2 - q, p1 - p2 - q, -p1 + p2 - q, -p1 - p2 - q}

|improve this answer|||||
$\endgroup$
  • $\begingroup$ Thanks for your answer. Can you give me an example of how to extend it for q,p1,p2,..pn $\endgroup$ – NeAr Feb 19 at 15:20
  • $\begingroup$ @user69814, i added a generalization for n variables. $\endgroup$ – kglr Feb 19 at 15:33
  • $\begingroup$ You are the best. Thanks alot :) $\endgroup$ – NeAr Feb 19 at 15:40
12
$\begingroup$
{q, p1, p2}*# & /@ Tuples[{+1, -1}, 3]

{{q, p1, p2}, {q, p1, -p2}, {q, -p1, p2}, {q, -p1, -p2}, {-q, p1, p2}, {-q, p1, -p2}, {-q, -p1, p2}, {-q, -p1, -p2}}

|improve this answer|||||
$\endgroup$

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.