Generate combinations with scaleable code

1 次查看(过去 30 天)
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
the cyclist 2022-12-29
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by