rand — Generate uniformly distributed pseudorandom numbers in [0, 1) with MATLAB-compatible syntax.
rand produces uniformly distributed pseudorandom numbers in [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
n- Type
SizeArg- Required
- Yes
- Description
- Square size.
size_vector- Type
SizeArg- Required
- Yes
- Description
- Size vector defining output dimensions.
dims- Type
SizeArg- Required
- Variadic
- Description
- Dimension sizes.
typename- Type
StringScalar- Required
- No
- Default
"double"- Description
- Class override ('double'|'single'|'gpuArray').
like_kw- Type
StringScalar- Required
- Yes
- Default
"like"- Description
- Like keyword.
prototype- Type
LikePrototype- Required
- Yes
- Description
- Prototype array used for class/device.
seed_option- Type
StringScalar- Required
- Yes
- Default
"seed"- Description
- Legacy seed query option.
seed_option- Type
StringScalar- Required
- Yes
- Default
"seed"- Description
- Legacy seed control option.
seed- Type
NumericScalar- Required
- Yes
- Description
- Non-negative integer seed.
Returns
A- Type
NumericArray- Description
- Uniform random array in [0,1).
seed- Type
NumericScalar- Description
- Legacy restorable RNG state token.
Errors
- When
- The 'like' keyword is provided without a prototype argument.
- Message
rand: expected prototype after 'like'
- When
- A trailing option string is not supported.
- Message
rand: unrecognised option
- When
- A prototype type cannot be used for rand(..., 'like', prototype).
- Message
rand: unsupported prototype
- When
- Dimension arguments fail numeric/shape parsing.
- Message
rand: dimension arguments must be numeric and nonnegative
Behavior
rand() returns a scalar double drawn uniformly from [0, 1).
rand(n) returns an n × n double 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 of A, while ordinary size arguments determine shape and omission of size arguments returns a scalar. The old implicit rand(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) and rand("seed", seed) read non-negative integer scalar seeds exactly and reset RunMat's CPU MT19937 stream. rand('seed') queries a same-session restorable RunMat token for the current CPU stream position; passing that token back restores subsequent CPU draws. This legacy control never reseeds the independent GPU child stream; use gpurng for GPU output. Exact MATLAB generator/state parity remains a separate RNG-engine conformance gap.
Execution and residency
Ordinary rand construction does not itself guarantee device residency. RunMat may select an accelerator for a larger admitted computation; use an explicit GPU form or a resident 'like' prototype when device residency is required.
Ordinary CPU output consumes the session stream controlled by rng. Explicit GPU or resident-like output consumes the independent GPU child stream controlled by gpurng; a selected provider may generate on device, or an admitted host-mediated route may compute from that same GPU stream and restore the exact owner. Automatic placement of ordinary output does not change its CPU stream sequence.
Examples
Creating a 3x3 matrix of random numbers
R = rand(3); % 3x3 doubles in [0, 1)Creating a 2x4x3 matrix of random numbers
sz = [2 4 3];
T = rand(sz)Creating a 128x128 matrix of random numbers
G = rand(128, 128)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);Seed CPU and GPU streams independently
rng(7); gpurng(11); a = rand(1,3); g = rand(1,3,'gpuArray'); gpurng(11); h = rand(1,3,'gpuArray')Expected output:
The two resident draws match after reseeding only the GPU streamUsing 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 arrays of pseudorandom numbers in [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 in [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 uniformly from [0, 1).
Should I use rand('seed', seed) or rng(seed)?⌄
rng(seed) is the preferred modern CPU-stream spelling. rand('seed', seed) remains supported for legacy scripts and returns a same-session CPU-state token on query. Use gpurng separately for GPU output.
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 · randi · 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 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 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.