RunMat
GitHub

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

NameTypeRequiredDefaultDescription
imaxIntegerScalarYesUpper bound; lower bound defaults to 1.
boundsNumericArrayYesTwo-element bounds vector [imin imax].
nSizeArgNoSquare size.
size_vectorSizeArgNoSize vector defining output dimensions.
dimsSizeArgVariadicDimension sizes.
boundsNumericArrayYesUpper bound scalar or two-element bounds vector.
typenameStringScalarNo"double"Class override ('double'|'logical').
like_kwStringScalarYes"like"Like keyword.
prototypeLikePrototypeYesPrototype array used for class/device.
prototypeLikePrototypeYesPrototype value when no numeric dimension arguments are provided.

Returns

NameTypeDescription
RNumericArrayUniform random integers.

Errors

IdentifierWhenMessage
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

How randi works

  • 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 both the shape and device residency of A, 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 = 1

Creating a matrix of random indices

rng(0);
idx = randi(10, 2, 3)

Expected output:

idx =
     1     9     7
    10     2     1

Generating 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     5

Matching 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
     1

Building 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     0

Reproducible 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.

Creation

colon · eye · false · fill · inf · linspace · logspace · magic · meshgrid · nan · ones · peaks · rand · randn · randperm · range · true · zeros

Sorting Sets

argsort · intersect · ismember · issorted · setdiff · sort · sortrows · union · unique

Shape

cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · squeeze · tril · triu · vertcat

Indexing

find · ind2sub · sub2ind

Introspection

isempty · ismatrix · isscalar · isvector · length · ndims · numel · size

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how randi is executed, line by line, in Rust.

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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.