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
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
imax | IntegerScalar | Yes | — | Upper bound; lower bound defaults to 1. |
bounds | NumericArray | Yes | — | Two-element bounds vector [imin imax]. |
n | SizeArg | No | — | Square size. |
size_vector | SizeArg | No | — | Size vector defining output dimensions. |
dims | SizeArg | Variadic | — | Dimension sizes. |
bounds | NumericArray | Yes | — | Upper bound scalar or two-element bounds vector. |
typename | StringScalar | No | "double" | Class override ('double'|'logical'). |
like_kw | StringScalar | Yes | "like" | Like keyword. |
prototype | LikePrototype | Yes | — | Prototype array used for class/device. |
prototype | LikePrototype | Yes | — | Prototype value when no numeric dimension arguments are provided. |
Returns
| Name | Type | Description |
|---|---|---|
R | NumericArray | Uniform random integers. |
Errors
| Identifier | When | Message |
|---|---|---|
| — | No bounds argument is provided. | randi: requires at least one input argument |
| — | Bounds are invalid or unsupported (empty, non-finite, non-integer, or malformed). | randi: bounds must be numeric scalars or vectors |
| — | Lower bound exceeds upper bound. | randi: lower bound must be <= upper bound |
| — | The 'like' keyword is provided without a prototype argument. | randi: expected prototype after 'like' |
| — | The 'like' keyword is provided multiple times. | randi: multiple 'like' specifications are not supported |
| — | A class keyword and a 'like' prototype are both provided. | randi: cannot combine 'like' with class specifiers |
| — | An unsupported output class is requested. | randi: output class is not implemented |
| — | A trailing option string is not recognized. | randi: unrecognised option |
| — | Dimension arguments fail numeric/shape parsing. | randi: dimension arguments must be numeric and nonnegative |
How randi works
randi(imax)returns a scalar double selected uniformly from1:imax.randi(imax, m, n, ...)creates dense arrays whose entries are in1:imax.randi([imin imax], sz)accepts a two-element range vector plus either a size vector or explicit dimensions.randi(___, 'like', A)matches both the shape and device residency ofA, including GPU tensors when acceleration is enabled.- Negative lower bounds are supported so long as
imin <= imax. randi(___, 'double')is accepted for MATLAB compatibility and keeps the default double output.randi(___, 'logical')emits a logical array when the inclusive range stays within[0, 1].- RunMat diagnoses unsupported class specifiers (e.g.,
'single','uint8') with descriptive errors until native representations land.
Does RunMat run randi on the GPU?
When the target output or 'like' prototype resides on the GPU, RunMat first asks the active acceleration provider for device-side generation via random_integer_like (shape reuse) or random_integer_range (explicit shape). Providers that do not expose these hooks fall back to host-side sampling followed by a single upload, ensuring correctness while still keeping the resulting tensor on the GPU.
GPU memory and residency
You usually do NOT need to call gpuArray yourself in RunMat (unlike MATLAB).
In RunMat, the fusion planner keeps residency on GPU in branches of fused expressions. As such, in the examples above, the result of randi remains on the GPU whenever the planner determines that downstream work benefits from staying on device.
To preserve backwards compatibility with MathWorks MATLAB—and when you want to be explicit about residency—you can call gpuArray yourself to seed GPU execution.
Because MathWorks MATLAB lacks a fusion planner and ships GPU support as a separate toolbox, MATLAB users must move data manually. RunMat automates residency to streamline accelerated workflows.
Examples
Drawing a single die roll
rng(0);
roll = randi(6)Expected output:
roll = 1Creating a matrix of random indices
rng(0);
idx = randi(10, 2, 3)Expected output:
idx =
1 9 7
10 2 1Generating bounded integers with a size vector
rng(0);
shape = [3 4 2];
tiles = randi([5 20], shape)Expected output:
tiles(:, :, 1) =
6 7 5 15
19 14 9 16
18 5 10 13
tiles(:, :, 2) =
20 5 17 8
20 14 5 9
10 9 18 5Matching an existing gpuArray
rng(0);
G = gpuArray.zeros(4, 4);
labels = randi([0 3], 'like', G);
peek = gather(labels)Expected output:
peek =
0 2 1 3
3 0 2 3
3 0 2 1
0 1 2 0
isa(labels, 'gpuArray')
ans =
logical
1Building a random logical mask
rng(0);
mask = randi([0 1], 4, 4, 'logical')Expected output:
mask =
0 1 0 1
1 0 1 1
1 0 1 0
0 0 1 0Reproducible integer tensors inside tests
rng(0);
p = randi([1 4], 1, 5)Expected output:
p = [1 4 4 1 3]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?⌄
RunMat matches MATLAB by storing results in double-precision tensors whose values are integers. Future releases will add direct integer array classes.
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 size vector (randi(9, [4 2])). Providing a 'like' prototype also copies the prototype's shape automatically.
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.
What happens if the provider lacks integer RNG hooks?⌄
RunMat falls back to host generation followed by a single upload. The resulting array still lives on the GPU; only the initial samples are produced on the CPU.
Does randi support 'single' or integer output classes?⌄
Not yet. The randi builtin currently supports doubles only. Supplying 'single' or integer class names raises a descriptive error.
Related Array functions
Creation
colon · eye · false · fill · inf · linspace · logspace · magic · meshgrid · nan · ones · peaks · rand · randn · randperm · range · true · zeros
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. 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 an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 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.