Matrix showing all combinations of multiple dice roll

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.

 Risposta accettata

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 Commenti

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

Accedi per commentare.

Più risposte (2)

Torsten
Torsten il 12 Ott 2018
https://de.mathworks.com/matlabcentral/fileexchange/10064-allcomb-varargin
Best wishes
Torsten.

1 Commento

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.

Accedi per commentare.

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 Commento

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)

Accedi per commentare.

Prodotti

Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by