Best way to generate an array of all possible integer numbers for a given base and number of digits

6 次查看(过去 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 CenterFile Exchange 中查找有关 Resizing 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