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!

採用された回答

Walter Roberson
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
S = 81×4
0 0 0 0 0 0 0 1 0 0 0 2 0 0 1 0 0 0 1 1 0 0 1 2 0 0 2 0 0 0 2 1 0 0 2 2 0 1 0 0

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by