All possible combination based on 2^n
조회 수: 2 (최근 30일)
이전 댓글 표시
I want to create a matrix containing all possible combination. Example of this is shown below. The size of the matrix depends on the number of variable n and the total of combination should follow the
. The example below is valid for
and, hence, the total number of rows is 8. The value of each element is 0 and 1.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/617478/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/617483/image.png)
How to create this matrix automatically depending on the number of variable n?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/617473/image.png)
댓글 수: 0
채택된 답변
추가 답변 (3개)
Dyuman Joshi
2021년 5월 14일
y = flipud(dec2bin(0:2^n-1,n))-'0' %method 1
y = dec2bin(2^n-1:-1:0,n)-'0' %method 2
Choose any of the methods you wish, both give the same result.
P.S - There is a similar question in Cody as well.
댓글 수: 2
Bjorn Gustavsson
2021년 5월 14일
You could use dec2bin:
allpossibles = dec2bin(0:(2^n-1));
You'll have to extract the indices from the columns but that should be "not hard". There's more than likely many prettier solutions, for example have a look on the file exchange for nextperm (by Jos) and next-combination-permutation (by Matt-Fig).
HTH
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!