Generate combinations with scaleable code

1 visualización (últimos 30 días)
Howard Wilton
Howard Wilton el 29 de Dic. de 2022
Comentada: Howard Wilton el 29 de Dic. de 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.

Respuesta aceptada

the cyclist
the cyclist el 29 de Dic. de 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

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by