2
$\begingroup$

I would want to create the vectors $(\pm x_1, \pm x_2, \ldots,\pm x_n), \; \{x_1,x_2,x_3 \in \mathbb R\}, \{n\in \mathbb N \}$.

For small $n$, this can be done manually (here $n=2, \, x_1 = 1, \, x_2 = 2$),

$(\pm 1, \pm 2) = \{(-1, -2), \;(1,-2), \; (-1,2), \;(1,2) \}$

but the number of vectors increases exponentially. Is there a neat built-in syntax for this kind of list manipulation?

$\endgroup$
3
  • 1
    $\begingroup$ Perhaps Tuples? $\endgroup$
    – Michael E2
    Commented Sep 27, 2016 at 18:05
  • 3
    $\begingroup$ x={1,2,3,4} and then Tuples[{-#, #}&/@x] or Tuples[Transpose[{-x, x}]] $\endgroup$
    – Coolwater
    Commented Sep 27, 2016 at 18:08
  • $\begingroup$ You have repeated set {-1,-2}!? $\endgroup$ Commented Sep 27, 2016 at 18:40

1 Answer 1

4
$\begingroup$

Like Coolwater pointed out in the comments you could use the built-in Tuples command:

Tuples[{-#,#}&/@Range[1,n]]

which works pretty fast.

Another (slow) but natural approach is using PatternMatching:

n=2;
Flatten[Table[PlusMinus[i],{i,1,n}]//.{a___,PlusMinus[b_],c___}:>{{a,b,c},{a,-b,c}},n-1]

{{1,2},{1,-2},{-1,2},{-1,-2}}

$\endgroup$
2
  • 1
    $\begingroup$ If one needs performance Distribute[{-#, #} & /@ Range[1, 5], List] is slightly faster than Tuples[{-#, #} & /@ Range[1, 5]] ;-) $\endgroup$
    – mgamer
    Commented Sep 27, 2016 at 20:54
  • $\begingroup$ Slot-free: Tuples[Outer[Times, Range[n], {-1, 1}]]. $\endgroup$ Commented Dec 11, 2016 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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