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

3 vues (au cours des 30 derniers jours)
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!

Réponse acceptée

Walter Roberson
Walter Roberson le 9 Juin 2021
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

Plus de réponses (0)

Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by