Best way to generate an array of all possible integer numbers for a given base and number of digits
4 views (last 30 days)
Show older comments
Bill Tubbs
on 8 Jun 2021
Answered: Walter Roberson
on 9 Jun 2021
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 Comments
Accepted Answer
Walter Roberson
on 9 Jun 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
0 Comments
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!