필터 지우기
필터 지우기

Generate combinations with scaleable code

조회 수: 2 (최근 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

추가 답변 (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