Generate combinations with scaleable code

1 回表示 (過去 30 日間)
Howard Wilton
Howard Wilton 2022 年 12 月 29 日
コメント済み: Howard Wilton 2022 年 12 月 29 日
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
  1 件のコメント
Howard Wilton
Howard Wilton 2022 年 12 月 29 日
Thanks very much. Neat!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by