randi — Generate uniform random integers in MATLAB and RunMat.
randi draws uniformly distributed random integers from inclusive ranges. Size forms, range forms, and 'like' behavior follow MATLAB semantics.
Syntax
R = randi(imax)
R = randi([imin imax])
R = randi(imax, n)
R = randi([imin imax], n)
R = randi(imax, size_vector)
R = randi([imin imax], size_vector)All supported randi forms
R = randi(imax)
R = randi([imin imax])
R = randi(imax, n)
R = randi([imin imax], n)
R = randi(imax, size_vector)
R = randi([imin imax], size_vector)
R = randi(imax, m, n, ...)
R = randi([imin imax], m, n, ...)
R = randi(..., typename)
R = randi(..., "like", prototype)
R = randi(bounds, prototype)Inputs
imax- Type
IntegerScalar- Required
- Yes
- Description
- Upper bound; lower bound defaults to 1.
bounds- Type
NumericArray- Required
- Yes
- Description
- Two-element bounds vector [imin imax].
n- Type
SizeArg- Required
- No
- Description
- Square size.
size_vector- Type
SizeArg- Required
- No
- Description
- Size vector defining output dimensions.
dims- Type
SizeArg- Required
- Variadic
- Description
- Dimension sizes.
bounds- Type
NumericArray- Required
- Yes
- Description
- Upper bound scalar or two-element bounds vector.
typename- Type
StringScalar- Required
- No
- Default
"double"- Description
- Output class override; int64 and uint64 are RunMat-mode extensions.
like_kw- Type
StringScalar- Required
- Yes
- Default
"like"- Description
- Like keyword.
prototype- Type
LikePrototype- Required
- Yes
- Description
- Prototype array used for class/device.
prototype- Type
LikePrototype- Required
- Yes
- Description
- RunMat-only shorthand that copies prototype shape and class without a like keyword.
Returns
R- Type
NumericArray- Description
- Uniform random integers.
Errors
- When
- No bounds argument is provided.
- Message
randi: requires at least one input argument
- When
- Bounds are invalid or unsupported (empty, non-finite, non-integer, or malformed).
- Message
randi: bounds must be numeric scalars or vectors
- When
- Lower bound exceeds upper bound.
- Message
randi: lower bound must be <= upper bound
Behavior
randi(imax) returns a scalar double selected uniformly from 1:imax.
randi(imax, m, n, ...) creates dense arrays whose entries are in 1:imax.
randi([imin imax], sz) accepts a two-element range vector plus either a size vector or explicit dimensions.
randi(___, 'like', A) matches the class, complexity where supported, and device residency of A; ordinary size arguments determine the output shape, and omitting them returns a scalar.
Negative lower bounds are supported so long as imin <= imax.
randi(___, 'double') is accepted for MATLAB compatibility and keeps the default double output.
randi(___, 'single'), randi(___, 'logical'), and the documented integer class names through uint32 preserve the requested output class; logical output requires the inclusive range to stay within [0, 1].
All eight integer classes are documented for size controls and are decoded structurally. If sampled bounds exceed the selected output class, conversion saturates values to that class's endpoints.
int64 and uint64 output classes are exact RunMat extensions available only in runmat compatibility mode.
The bare randi(bounds, prototype) shorthand copies prototype shape and class only in runmat mode; MATLAB-compatible code uses explicit dimensions and the like keyword.
Execution and residency
Ordinary randi construction does not guarantee GPU residency. A resident 'like' prototype requests an output on its exact owning provider, and an explicit gpuArray conversion can move an ordinary result to the device. RunMat may select accelerated placement for a larger admitted computation, but an active provider alone does not make these ordinary examples GPU-resident.
Ordinary output draws from the CPU stream controlled by rng. Explicit resident output draws from the independent GPU child stream controlled by gpurng, using unbiased full-width host computation from that GPU child range and typed upload through the exact owner. There is no post-effect redraw on another stream.
Examples
Drawing a single die roll
rng(0);
roll = randi(6)Creating a matrix of random indices
rng(0);
idx = randi(10, 2, 3)Generating bounded integers with a size vector
rng(0);
shape = [3 4 2];
tiles = randi([5 20], shape)Matching an existing gpuArray
gpurng(0);
G = gpuArray.zeros(4, 4);
labels = randi([0 3], 4, 4, 'like', G);
peek = gather(labels)Building a random logical mask
rng(0);
mask = randi([0 1], 4, 4, 'logical')Reproducible integer tensors inside tests
rng(0);
p = randi([1 4], 1, 5)Using randi with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how randi changes the result.
Run a small randi example, explain the result, then change one input and compare the output.
FAQ
What range does randi(imax) use?⌄
The call randi(imax) produces integers in the inclusive range 1:imax. Use the two-element form randi([imin imax], ...) when you need a custom minimum.
Can the lower bound be negative?⌄
Yes. randi([imin imax], ...) accepts negative bounds as long as imin <= imax and both bounds are integers.
Does randi return doubles or integer arrays?⌄
The default result is double. A documented class name or 'like' prototype can select native single, logical, or integer storage; int64 and uint64 output are additional runmat-mode extensions.
Can I request a logical result directly?⌄
Yes. Pass 'logical' as the final argument, and ensure the inclusive range stays within [0, 1]. Any other range produces an error because logical arrays can only store 0/1 values.
How do I control the array shape?⌄
Pass either explicit dimensions (randi(9, 4, 2)) or a row size vector (randi(9, [4 2])). A 'like' prototype selects class, complexity, and residency but does not copy shape; omitting dimensions returns a scalar.
How does randi interact with rng?⌄
randi consumes RunMat's global RNG stream. Use the MATLAB-compatible rng builtin to seed or restore the generator for reproducible simulations.
How is a resident randi result generated?⌄
It consumes the GPU child stream controlled by gpurng, independently of rng. The preselected host-compute/typed-upload route retains the exact owner and output class; operational failure is not replayed.
Does randi support 'single' or integer output classes?⌄
Yes. single, int8, int16, int32, uint8, uint16, and uint32 are available in MATLAB-compatible modes. Exact int64 and uint64 output is deliberately gated to runmat mode.
Related Array functions
Creation
colon · createArray · empty · eye · false · full · inf · int16.empty · int32.empty · int64.empty · int8.empty · linspace · logspace · magic · meshgrid · nan · ndgrid · nonzeros · ones · peaks · rand · randn · randperm · range · sparse · spdiags · speye · spones · sprand · true · uint16.empty · uint32.empty · uint64.empty · uint8.empty · zeros
Accumulation
Sorting Sets
argsort · intersect · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sort · sortrows · union · unique
Shape
blkdiag · cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · shiftdim · squeeze · toeplitz · tril · triu · vertcat
Combinatorics
Binning
Grouping
Source you can read
Every RunMat function's source is public. Read exactly how randi is executed, line by line, in Rust.
- View the source for randi in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.