randi

Random integers drawn uniformly from a range.

Category: Mathematics > Random Number Generation

Syntax

r = randi(imax)

Returns one integer from 1 to imax.

r = randi(imax, n)

Returns an n-by-n matrix.

r = randi(imax, sz1, ..., szN)

Returns an array with the given dimensions.

r = randi([imin imax], ___)

Draws from imin to imax instead of starting at 1.

r = randi(___, classname)

Returns integers of the given class, such as 'int8' or 'uint16'.

Description

Each element is an independent draw from the discrete uniform distribution on the range. The values come from the global random stream, so rng makes them repeatable.

The result is a double by default even though the values are whole numbers. Passing an integer class gives a compact array of that type.

Input arguments

imax
Positive integer: the largest value possible.
[imin imax]
Two-element vector with imin <= imax; negatives are allowed.
classname
Result class: 'double' (default), 'single' or an integer class.

Output arguments

r
Array of integers, every value in the range equally likely.

Example

Dice, a range and an integer class

rng(1);
randi(6, 1, 8)
randi([-2 2], 2, 3)
class(randi(9, 2, 'uint8'))
Output
ans = 1×8

     3     5     1     2     1     1     2     3
ans = 2×3

    -1     0    -1
     0     1     2
ans = 'uint8'

Notes

The generator is seeded like MATLAB's, but the integers produced for a given seed may differ from the ones MATLAB gives.

See also

rand randn randperm rng RandStream