Matrix showing all combinations of multiple dice roll

2 views (last 30 days)
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.

Accepted Answer

Bruno Luong
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
Nicolas Tarino
Nicolas Tarino on 13 Oct 2018
Nice! I don't completely get your code yet, but it works fast (enough) and fine.
Bruno Luong
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.

Sign in to comment.

More Answers (2)

Torsten
Torsten on 12 Oct 2018
https://de.mathworks.com/matlabcentral/fileexchange/10064-allcomb-varargin
Best wishes
Torsten.
  1 Comment
Nicolas Tarino
Nicolas Tarino on 13 Oct 2018
Not as fast as Bruno's code, but I really appreciate the fact that you can have multiple different dice entries instead of just 1:n.

Sign in to comment.


Image Analyst
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).
  1 Comment
Nicolas Tarino
Nicolas Tarino on 13 Oct 2018
Nope, the number of dice is not known in advance. That's what ruled out nested for loops for me. Meanwhile I might be able to do this by recursion... but it should be way too slow for large dimensions (or number of dice)

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!