Best way to generate an array of all possible integer numbers for a given base and number of digits
조회 수: 4 (최근 30일)
이전 댓글 표시
I want to prepare an array that contains all combinations in rows of possible sequences represented by an d-digit number of base b.
E.g. With n = 3 and b = 2 I came up with the following two ways to do it
d = 3; b = 2; n = b^n-1;
S = dec2base(0:n-1,b) == '1'
S =
7×3 logical array
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
This method works for d <=3 but not higher:
[B1,B2,B3] = meshgrid(0:b-1,0:b-1,0:b-1);
S = [B1(:) B2(:) B3(:)]
S =
0 0 0
0 1 0
1 0 0
1 1 0
0 0 1
0 1 1
1 0 1
1 1 1
The order of the sequences doesn't matter.
I'm sure there must be a simpler way!
댓글 수: 0
채택된 답변
Walter Roberson
2021년 6월 9일
d = 4; b = 3;
B = cell(1,d);
[B{:}] = ndgrid(0:b-1);
B = cellfun(@(M) M(:), B, 'uniform', 0);
S = [B{end:-1:1}];
S
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!