# Generate combinations with scaleable code

2 views (last 30 days)
Howard Wilton on 29 Dec 2022
Commented: Howard Wilton on 29 Dec 2022
I have a tight piece of code which generates a 16x4 matrix which essentially is 16 vectors with 4 elements each and i want all the combinations where the vector elements are -1 or 1
[a1,a2,a3,a4] = ndgrid([1 -1],[1 -1],[1 -1],[1 -1]);
a_all_combos = [a1(:),a2(:),a3(:),a4(:)]
clear a1 a2 a3 a4
The code yields the following output:
1 1 1 1
-1 1 1 1
1 -1 1 1
-1 -1 1 1
1 1 -1 1
-1 1 -1 1
1 -1 -1 1
-1 -1 -1 1
1 1 1 -1
-1 1 1 -1
1 -1 1 -1
-1 -1 1 -1
1 1 -1 -1
-1 1 -1 -1
1 -1 -1 -1
-1 -1 -1 -1
However, this code does not scale-up nicely if I want nine-element vectors, yielding a x9 matrix.
Would welcome any suggestions on how to do this concisely.

the cyclist on 29 Dec 2022
There happens to be a quite obfuscated way to do this:
n = 9;
a_all_combos = 2*(dec2bin(0:2^n-1) - '0') - 1
a_all_combos = 512×9
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 1 -1 -1 -1 -1 -1 -1 -1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 -1 -1 -1 -1 -1 -1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1 -1 -1 1 1 -1 -1 -1 -1 -1 -1 -1 1 1 1 -1 -1 -1 -1 -1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 -1 -1 1
Howard Wilton on 29 Dec 2022
Thanks very much. Neat!

### Categories

Find more on Matrices and Arrays in Help Center and File Exchange

R2020b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!