Matrix showing all combinations of multiple dice roll
2 views (last 30 days)
Show older comments
I want to create a matrix showing all possible combinations of tossing n independent dice rolls, except that dice is not always 6-sided.
e.g. I want to create matrix res
res = [1,1,1;
1,1,2;
1,2,1;
1,2,2;
2,1,1;
2,1,2;
2,2,1;
2,2,2];
using a vector v = [2,2,2]. Basically vector v specifies the number and size of each dice. Is there a fast way to iterate this without using for loop? I know if the dice size is constant I can use:
res = dec2base(0:dice_size^n-1,dice_size) - '0';
res = res + 1;
But I am stuck when each dice has different sizes.
0 Comments
Accepted Answer
Bruno Luong
on 12 Oct 2018
dice_size=[2 3 4];
n = length(dice_size);
c = arrayfun(@(n) 1:n, flip(dice_size), 'unif', 0);
[c{:}] = ndgrid(c{:});
c = cat(n+1,c{:});
c = fliplr(reshape(c,[],n))
c =
1 1 1
1 1 2
1 1 3
1 1 4
1 2 1
1 2 2
1 2 3
1 2 4
1 3 1
1 3 2
1 3 3
1 3 4
2 1 1
2 1 2
2 1 3
2 1 4
2 2 1
2 2 2
2 2 3
2 2 4
2 3 1
2 3 2
2 3 3
2 3 4
2 Comments
Bruno Luong
on 13 Oct 2018
Edited: Bruno Luong
on 13 Oct 2018
If the order of the combinations is not matter for you, you can remove the FLIP and FLIPLR instructions to make it even faster.
More Answers (2)
Torsten
on 12 Oct 2018
https://de.mathworks.com/matlabcentral/fileexchange/10064-allcomb-varargin
Best wishes
Torsten.
Image Analyst
on 12 Oct 2018
ndgrid or meshgrid is what experienced MATLABers would use. For beginners, a set of nested for loops would work if the number of dice was known in advance (like 3) and not a variable (like n=3).
See Also
Categories
Find more on Creating and Concatenating 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!