rand — Generate uniformly distributed pseudorandom numbers on the open interval (0, 1) with MATLAB-compatible syntax.
rand produces uniformly distributed pseudorandom numbers over the open interval (0, 1). It supports MATLAB-compatible size forms, single/double class selection, 'like' prototypes that control output type, complexity, and residency, and the legacy rand('seed', seed) control form.
Syntax
A = rand()
A = rand(n)
A = rand(size_vector)
A = rand(m, n, ...)
A = rand(..., typename)
A = rand(..., "like", prototype)
seed = rand("seed")
rand("seed", seed)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
n | SizeArg | Yes | — | Square size. |
size_vector | SizeArg | Yes | — | Size vector defining output dimensions. |
dims | SizeArg | Variadic | — | Dimension sizes. |
typename | StringScalar | No | "double" | Class override ('double'|'single'|'gpuArray'). |
like_kw | StringScalar | Yes | "like" | Like keyword. |
prototype | LikePrototype | Yes | — | Prototype array used for class/device. |
seed_option | StringScalar | Yes | "seed" | Legacy seed query option. |
seed_option | StringScalar | Yes | "seed" | Legacy seed control option. |
seed | NumericScalar | Yes | — | Non-negative integer seed. |
Returns
| Name | Type | Description |
|---|---|---|
A | NumericArray | Uniform random array in (0,1). |
seed | NumericScalar | Legacy restorable RNG state token. |
Errors
| Identifier | When | Message |
|---|---|---|
| — | The 'like' keyword is provided without a prototype argument. | rand: expected prototype after 'like' |
| — | A trailing option string is not supported. | rand: unrecognised option |
| — | A prototype type cannot be used for rand(..., 'like', prototype). | rand: unsupported prototype |
| — | Dimension arguments fail numeric/shape parsing. | rand: dimension arguments must be numeric and nonnegative |
How rand works
rand()returns a scalar double drawn fromU(0, 1).rand(n)returns ann × ndouble matrix.rand(m, n, ...)returns a dense double array of the requested dimensions.rand(sz)accepts a documented row size vector; a column size vector is an independently gated RunMat-mode extension.- All eight integer classes are documented for scalar, separate-dimension, and row-size-vector controls and are decoded structurally from authoritative storage; resident size controls are separately gated RunMat extensions.
rand(___, 'like', A)matches the type, complexity, and residency ofA, while ordinary size arguments determine shape and omission of size arguments returns a scalar. The old implicitrand(A)prototype form is not supported.rand(___, 'double')leaves the output as double precision (default).'single'returns single-precision results that mirror MATLAB's behaviour.rand('seed', seed)andrand("seed", seed)read non-negative integer scalar seeds exactly and reset RunMat's shared pseudorandom stream.rand('seed')queries a same-session restorable RunMat token for the current stream position; passing that token back restores subsequent RunMat draws. This legacy control form also synchronizes the active acceleration provider's RNG state when provider hooks are available; exact MATLAB generator/state parity remains a separate RNG-engine conformance gap.
Does RunMat run rand on the GPU?
When the prototype lives on the GPU, RunMat first asks the active acceleration provider for a device-side random buffer via random_uniform / random_uniform_like. If the provider lacks those hooks, RunMat generates samples on the host and uploads them to maintain GPU residency. This guarantees MATLAB-compatible behaviour while documenting the extra transfer cost.
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 above example, the result of the rand call will already be on the GPU when the fusion planner has detected a net benefit to operating the fused expression it is part of on the GPU.
To preserve backwards compatibility with MathWorks MATLAB, and for when you want to explicitly bootstrap GPU residency, you can call gpuArray explicitly to move data to the GPU if you want to be explicit about the residency.
Since MathWorks MATLAB does not have a fusion planner, and they kept their parallel execution toolbox separate from the core language, as their toolbox is a separate commercial product, MathWorks MATLAB users need to call gpuArray to move data to the GPU manually whereas RunMat users can rely on the fusion planner to keep data on the GPU automatically.
Examples
Creating a 3x3 matrix of random numbers
R = rand(3); % 3x3 doubles in (0, 1)Expected output:
R = [0.8147 0.9134 0.1270; 0.9058 0.6324 0.0975; 0.1270 0.0975 0.2785]Creating a 2x4x3 matrix of random numbers
sz = [2 4 3];
T = rand(sz)Expected output:
T = [0.8147 0.9134 0.1270 0.9058 0.6324 0.0975 0.1270 0.0975 0.2785; 0.9134 0.6324 0.0975 0.2785 0.0975 0.1270 0.9058 0.6324 0.0975]Creating a 128x128 matrix of random numbers on a GPU
G = rand(128, 128)Expected output:
H = [0.8147 0.9134 0.1270 0.9058 0.6324 0.0975 0.1270 0.0975 0.2785; 0.9134 0.6324 0.0975 0.2785 0.0975 0.1270 0.9058 0.6324 0.0975]Use legacy seed syntax
rand('seed', 2026);
a = rand(1, 4);
s = rand('seed');
b = rand(1, 4);
rand('seed', s);
c = rand(1, 4);Expected output:
b and c contain the same values because s restores the post-a stream position.Using rand with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how rand changes the result.
Run a small rand example, explain the result, then change one input and compare the output.
FAQ
When should I use the rand function?⌄
Use rand whenever you need to create arrays filled with random numbers over the open interval (0, 1). This is useful for Monte Carlo simulations, generating noise for testing, or creating random initial conditions for optimization.
Does rand produce double arrays by default?⌄
Yes, by default, rand creates dense double-precision arrays unless you explicitly specify a type such as 'single' or use the 'like' argument to match a prototype array.
What does rand(n) return?⌄
rand(n) returns an n × n dense double-precision matrix filled with random numbers over the open interval (0, 1). For example, rand(3) yields a 3-by-3 matrix of random numbers.
How do I create a single precision array of random numbers?⌄
Pass 'single' as the last argument:
S = rand(5, 5, 'single');This produces a 5x5 single precision matrix of random numbers.
How do I match the type and device residency of an existing array?⌄
Use the 'like', prototype syntax:
A = gpuArray(rand(2,2));
B = rand(2, 2, 'like', A);B will have the prototype's type, complexity, and residency; the explicit dimensions determine its shape.
Can I create N-dimensional arrays with rand?⌄
Yes! Pass more than two dimension arguments (or a size vector):
T = rand(2, 3, 4);This creates a 2×3×4 tensor of random numbers.
Does rand(A) infer a prototype from an array?⌄
No. Use rand(..., 'like', A) to select type, complexity, and residency, and pass dimensions explicitly when the result should have a particular shape.
Is the output always dense?⌄
Yes. rand always produces a dense array. For sparse matrices of random numbers, use sparse with appropriate arguments.
What if I call rand with no arguments?⌄
rand() returns a scalar double drawn from U(0, 1).
Should I use rand('seed', seed) or rng(seed)?⌄
rng(seed) is the preferred modern spelling. rand('seed', seed) remains supported for legacy MATLAB scripts and maps to RunMat's shared random generator state. rand('seed') returns an opaque numeric state token intended for same-session save/restore workflows.
Related Array functions
Creation
colon · createArray · empty · eye · false · full · inf · linspace · logspace · magic · meshgrid · nan · nchoosek · ndgrid · nonzeros · ones · peaks · perms · randi · randn · randperm · range · sparse · spdiags · speye · spones · sprand · true · zeros
Grouping
accumarray · combinations · discretize · findgroups · groupcounts · grp2idx · splitapply
Sorting Sets
argsort · intersect · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sort · sortrows · union · unique
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how rand is executed, line by line, in Rust.
- View the source for rand 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.