RunMat
GitHub

rng — Configure, query, and restore the global pseudorandom number generator state with MATLAB-compatible forms.

rng queries or reconfigures the global pseudorandom number generator used by rand, randn, randi, and randperm. It supports MATLAB-compatible default, seeded, shuffled, and state-restore workflows.

Syntax

s = rng()
s = rng(seed)
s = rng(option)
s = rng(state)
s = rng(seed, generator)
s = rng(option, generator)

Inputs

NameTypeRequiredDefaultDescription
seedAnyYesNon-negative integer seed.
optionStringScalarYesOption token: 'default' or 'shuffle'.
stateAnyYesState struct containing Type, optional Seed, and State fields.
generatorStringScalarYes"twister"Generator token (currently only 'twister'/'default'/'runmat-lcg').

Returns

NameTypeDescription
sAnyRNG state snapshot struct with fields Type, Seed, and State.

Errors

IdentifierWhenMessage
RunMat:rng:SeedMustBeNonnegativeSeed value is negative.rng: seed must be non-negative
RunMat:rng:GeneratorUnsupportedGenerator token is unsupported.rng: generator is not supported
RunMat:rng:StateTypeFieldMissingState struct is missing the Type field.rng: state struct is missing the 'Type' field

How rng works

  • rng() returns a structure describing the current generator (fields Type, Seed, and State).
  • rng(seed) switches to the default generator with the supplied non-negative integer seed. Passing 0 reproduces MATLAB's rng('default').
  • rng('default') restores the default generator and seed (twister, seed 0).
  • rng('shuffle') seeds the generator with entropy derived from the current time.
  • rng(seed, 'twister') explicitly names the generator. RunMat currently supports twister, matching MATLAB's default stream.
  • rng(S) restores a state structure previously returned by rng. Whenever an acceleration provider is active, RunMat also pushes the new seed to the provider so GPU-resident random calls remain in sync with CPU sampling. Providers that lack set_rng_state simply fall back to their existing behaviour, which is documented below.

GPU memory and residency

RunMat pushes the configured seed to the active acceleration provider whenever rng changes the host generator. Providers that expose set_rng_state (runmat-accelerate's in-process and WGPU backends) therefore produce the same sequences as CPU rand/randn when seeded via rng. If a provider omits this hook, RunMat logs a debug message and continues with the provider's internal seed stream; in that case GPU draws may differ from CPU draws even after calling rng. You do not need to call gpuArray explicitly for residency purposes—RunMat keeps GPU streams in sync automatically whenever the provider supports RNG state injection.

Examples

Resetting the generator for reproducible simulation runs

rng(0);
rand(1, 4)

Expected output:

0.3969    0.8408    0.4221    0.6260

Saving 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 state

Expected output:

A =
    0.6406   -0.8022
    0.2222   -0.7161

B =
    0.3969    0.8408
    0.4221    0.6260

Scrambling the generator with the system clock

rng('shuffle');
u = rand(1, 3)

Expected output:

u =
    0.1378    0.7086    0.8463

Keeping CPU and GPU random draws in sync

rng(2024);
G = gpuArray(rand(1, 3));
C = gather(G);
H = rand(1, 3);         % same values as C

Expected output:

C =
    0.6554    0.7501    0.6046

H =
    0.6554    0.7501    0.6046

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

Using 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 exposes MATLAB's default 'twister' stream. Additional generators ('philox', 'combRecursive', etc.) will surface as the underlying engines land.

What numeric range is valid for seeds?

Any finite, non-negative integer representable exactly in double precision (0 <= seed <= 2^53) is accepted. Values outside this range produce an error.

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?

Yes—if the active acceleration provider implements set_rng_state. The bundled in-process reference provider and the WGPU backend both honour this hook.

How do I restore a saved state structure?

Pass the structure back to rng: s = rng; ...; rng(s); resumes where the original state left off, matching MATLAB behaviour.

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.

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how rng 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.