rng — Configure, query, and restore RunMat's global pseudorandom number generator through MATLAB-shaped forms.
rng queries or reconfigures the global pseudorandom number generator used by rand, randn, randi, and randperm. The call shapes and integer seed domain follow the compatibility target's surface, while RunMat's current LCG sequence and compact state representation are not MATLAB stream/state equivalents.
Syntax
s = rng()
s = rng(seed)
s = rng(option)
s = rng(state)
s = rng(seed, generator)
s = rng(option, generator)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
seed | Any | Yes | — | Non-negative integer seed. |
option | StringScalar | Yes | — | Option token: 'default' or 'shuffle'. |
state | Any | Yes | — | State struct containing Type, optional Seed, and State fields. |
generator | StringScalar | Yes | "twister" | Generator token (currently only 'twister'/'default'/'runmat-lcg'). |
Returns
| Name | Type | Description |
|---|---|---|
s | Any | RNG state snapshot struct with fields Type, Seed, and State. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:rng:SeedMustBeNonnegative | Seed value is negative. | rng: seed must be non-negative |
RunMat:rng:GeneratorUnsupported | Generator token is unsupported. | rng: generator is not supported |
RunMat:rng:StateTypeFieldMissing | State struct is missing the Type field. | rng: state struct is missing the 'Type' field |
RunMat:rng:InvalidArgument | Arguments are missing, malformed, or incompatible with supported forms. | rng: invalid argument |
RunMat:rng:Internal | Internal snapshot conversion/allocation/apply fails. | rng: internal operation failed |
How rng works
rng()returns a structure describing the current generator (fieldsType,Seed, andState).rng(seed)reads a non-negative integer seed below2^32from scalar double or any of the eight native integer classes. Seeds at or above2^32are an independently gated RunMat extension.rng('default')restores RunMat's default LCG state and user seed0; this is reproducible inside RunMat but does not claim MATLAB Twister sequence equivalence.rng('shuffle')seeds the generator with entropy derived from the current time.rng(seed, 'twister')is accepted as the public generator spelling, but the current RunMat engine remains an LCG and does not yet reproduce MATLAB Twister sequences.rng(S)restores a state structure previously returned by RunMat'srng. Independently constructed native-integer Seed or State fields are a gated RunMat extension. Whenever an acceleration provider is active, RunMat pushes its compact state token to the provider when supported; this coordinates RunMat streams but does not establish MATLAB CPU/GPU sequence equivalence.
GPU memory and residency
RunMat pushes its compact state token to the active acceleration provider whenever rng changes the host generator. A provider that implements set_rng_state can coordinate its RunMat stream with that token; providers without the hook retain their own stream. This mechanism is independent of automatic tensor residency and does not claim MATLAB CPU/GPU sequence equivalence.
Examples
Resetting the generator for reproducible simulation runs
rng(0);
rand(1, 4)Expected output:
0.3969 0.8408 0.4221 0.6260Saving and restoring RNG state around a computation
s = rng;
rng(1337);
A = randn(2, 2);
rng(s); % restore original stream
B = randn(2, 2); % continues from the saved stateExpected output:
A =
0.6406 -0.8022
0.2222 -0.7161
B =
0.3969 0.8408
0.4221 0.6260Scrambling the generator with the system clock
rng('shuffle');
u = rand(1, 3)Expected output:
u =
0.1378 0.7086 0.8463Keeping CPU and GPU random draws in sync
rng(2024);
G = gpuArray(rand(1, 3));
C = gather(G);
H = rand(1, 3); % same values as CExpected output:
C =
0.6554 0.7501 0.6046
H =
0.6554 0.7501 0.6046Creating deterministic permutations with rng and randperm
rng(42);
p = randperm(6);
rng(42);
q = randperm(6)Expected output:
p =
6 2 1 4 3 5
q =
6 2 1 4 3 5Using rng with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how rng changes the result.
Run a small rng example, explain the result, then change one input and compare the output.
FAQ
What generators does RunMat support?⌄
RunMat currently uses its own deterministic LCG while accepting the public 'twister' spelling at the API boundary. Exact Twister sequence/state compatibility and additional generators remain future engine work.
What numeric range is valid for seeds?⌄
MATLAB-compatible mode accepts non-negative integer seeds below 2^32. RunMat mode extends the domain through u64; typed values remain exact, and snapshot Seed fields use native uint64 when binary64 would round.
How can I force a specific seed for rng('shuffle') in tests?⌄
Set the environment variable RUNMAT_RNG_SHUFFLE_SEED to an unsigned integer before calling rng('shuffle'). RunMat uses that value instead of system time.
Does rng affect GPU random numbers?⌄
RunMat forwards its compact state token when the active provider implements set_rng_state. This coordinates RunMat host/provider state, but it does not claim MATLAB CPU/GPU random-sequence identity.
How do I restore a saved state structure?⌄
Pass a structure returned by the same RunMat build back to rng: s = rng; ...; rng(s); resumes that RunMat stream. The compact structure is not a MATLAB Twister state interchange format.
What is stored in the State field?⌄
RunMat serialises the 64-bit internal state into a 1×2 double tensor containing the low and high 32-bit words. Feeding that tensor back to rng recreates the exact state.
Can I create independent streams?⌄
Not yet. RunMat exposes MATLAB-compatible RandStream APIs in a separate roadmap item; for now rng operates on the single global stream.
Does rng change automatically when I call other random functions?⌄
No. Only explicit calls to rng, RandStream, or provider-specific utilities reconfigure the seed. Sampling routines (rand, randn, randperm, etc.) consume the current stream but do not reseed it.
Related Stats functions
Random
binornd · bootstrp · datasample · dividerand · exprnd · gamrnd · lhsdesign · mvnrnd · normrnd · random · randsample · trnd · unidrnd · unifrnd · wblrnd
Ml
bayesopt · classify · confusionmat · crossvalind · cvpartition · fitclinear · fitctree · fitlm · kmeans · knnsearch · lasso · lassoglm · linkage · lscov · mnrfit · optimizableVariable · pdist · pdist2 · perfcurve · predict · regress · ridge · squareform · test · training · tsne
Summary
binocdf · boxplot · cdf · cdfplot · chi2cdf · corr · corrcoef · corrcov · cov · cov2corr · dummyvar · ecdf · filloutliers · fitdist · geomean · grpstats · harmmean · icdf · isoutlier · kstest · kurtosis · lsline · mad · mode · nanmax · normalize · normcdf · norminv · normpdf · onehotdecode · onehotencode · pdf · prctile · quantile · refline · rmse · skewness · tabulate · tcdf · tiedrank · tinv · tpdf · ttest2 · wblinv
Hist
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how rng is executed, line by line, in Rust.
- View the source for rng 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.