A dice roller for Matlab

version (2.54 KB) by Jonas
Everyone needs to roll dice or flip a coin now and then. This is the program to make it easy.


Updated 26 Apr 2010

View License

SYNOPSIS: [total, details] = roll(str)

INPUT str: Dice to be rolled. XdY, where X and Y are scalars, rolls X
fair Y-sided dice. Both X and Y are necessary.
If str is empty or omitted, '1d20' is used as default.

ROLL replaces the dice expression(s) by the rolled result, and
then evaluates the string. This makes it possible to use any
function call as input to ROLL as long as the function name
does not contain the signature of a roll (i.e. a number
followed by the letter 'd' followed by a number). In practice,
if you use ROLL for games, you most likely need only + and -.

There is one special function, XdYbZ, that takes the best Z
rolls out of the X attempts. This is useful to generate
character abilities in role-playing games.

OUTPUT total: total of the roll
details: individual rolls (cell array with results for each
dice in the input

REMARKS (1) If no output is requested, results are printed to screen
(2) Thanks to John D'Errico for pointing out that it is possible
to use any function with roll (as long as it takes the
results of dice rolls as input)

EXAMPLES roll 2d6 rolls two 6-sided dice
roll 1d8+1d4-2 rolls a 8-sided dice, a 4-sided dice and subtracts
2 from the result
roll 1d2 rolls a 2-sided dice (i.e. a coin flip)
roll log(2^1d6) takes the natural logarithm of 2 to the power of
the result of the roll of a 6-sided dice.
roll 1+1 throws an error, because there are no dice to roll.

Cite As

Jonas (2022). A dice roller for Matlab (https://www.mathworks.com/matlabcentral/fileexchange/27327-a-dice-roller-for-matlab), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2009a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!