randperm — Generate random permutations in MATLAB and RunMat.
randperm(n) returns a random permutation of integers 1:n. randperm(n, k) returns k unique values without replacement, with RNG and shape behavior following MATLAB semantics.
Syntax
p = randperm(n)
p = randperm(n, k)
p = randperm(n, "double")
p = randperm(n, k, "double")
p = randperm(n, "like", prototype)
p = randperm(n, k, "like", prototype)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
n | SizeArg | Yes | — | Population size. |
k | SizeArg | No | — | Number of selected elements. |
typename | StringScalar | No | "double" | Class override ('double'). |
like_kw | StringScalar | Yes | "like" | Like keyword. |
prototype | LikePrototype | Yes | — | Prototype array used for class/device. |
Returns
| Name | Type | Description |
|---|---|---|
p | NumericArray | Row vector containing permutation values. |
Errors
| Identifier | When | Message |
|---|---|---|
| — | No N argument is provided. | randperm: requires at least one input argument |
| — | N or K is not a supported non-negative integer scalar. | randperm: N/K must be non-negative integers |
| — | K is larger than N. | randperm: K must satisfy 0 <= K <= N |
| — | The 'like' keyword is provided without a prototype argument. | randperm: expected prototype after 'like' |
| — | The 'like' keyword is provided multiple times. | randperm: duplicate 'like' prototype specified |
| — | A class keyword and a 'like' prototype are both provided. | randperm: cannot combine 'double' with a 'like' prototype |
| — | An unsupported output class is requested. | randperm: single precision output is not implemented yet |
| — | A trailing option string is not recognized. | randperm: unrecognised option |
How randperm works
randperm(n)produces a row vector whose length isnand whose entries are a random ordering of1:n.randperm(n, k)returns the firstkentries of the permutation without replacement (0 ≤ k ≤ n). The result is a1 × krow vector.- Both
nandkaccept all eight documented integer classes and are decoded exactly as structural counts; ordinary output remains double. - In
runmatcompatibility mode, the RunMat-onlyrandperm(n, ___, 'like', A)selector preserves GPU residency whenAis resident while output remains double. - In
runmatcompatibility mode, the RunMat-only explicit'double'selector keeps the default double-precision output. randpermerrors whennorkare non-integers, negative, or exceed the IEEEdoubleinteger precision limit (2^53).- Empty permutations (e.g.,
randperm(0)orrandperm(n, 0)) return a1×0tensor.
Does RunMat run randperm on the GPU?
In runmat compatibility mode, when the RunMat-only 'like' prototype lives on the GPU, RunMat asks the active acceleration provider for a device-side permutation via the dedicated random_permutation_like hook. The bundled WGPU provider executes the entire selection and shuffle in a compute kernel, keeping the data resident on the device. Providers that do not advertise this hook fall back to the host implementation and upload the result once, preserving correctness while highlighting the extra transfer cost.
GPU memory and residency
You usually do NOT need to call gpuArray yourself in RunMat. In runmat compatibility mode, the RunMat-only 'like' selector can explicitly request a GPU-resident permutation from a resident prototype; providers without the permutation hook fall back to host generation followed by one upload.
Examples
Getting a random permutation of integers 1 through N
rng(0);
p = randperm(6)Expected output:
p = [1 6 2 4 3 5]Selecting K unique indices without replacement
rng(0);
idx = randperm(10, 3)Expected output:
idx = [1 10 9]Generating a reproducible permutation after seeding RNG
rng(42);
p1 = randperm(8);
rng(42);
p2 = randperm(8)Expected output:
isequal(p1, p2)
ans = logical
1Creating a resident random permutation
G = gpuArray.zeros(4, 4);
p = randperm(12, 4, 'like', G);
peek = gather(p)Expected output:
isa(p, 'gpuArray')
ans = logical
1Working with empty permutations
p = randperm(0);
q = randperm(5, 0)Expected output:
size(p)
ans =
1 0
size(q)
ans =
1 0Using randperm with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how randperm changes the result.
Run a small randperm example, explain the result, then change one input and compare the output.
FAQ
What ranges does randperm draw from?⌄
randperm(n) always returns integers in the inclusive range 1:n. The optional second argument k picks the first k elements of that permutation.
Can k be zero?⌄
Yes. randperm(n, 0) returns a 1×0 empty row vector without consuming any additional random numbers.
Does randperm support 'single' or integer output types?⌄
The result is always double. Supplying 'single' or integer class names raises a descriptive error; the explicit 'double' and 'like' selectors are available only in runmat compatibility mode.
How does randperm interact with rng?⌄
randperm consumes the shared RunMat RNG stream. Use the MATLAB-compatible rng builtin to seed or restore the generator for reproducible permutations.
Why is there a 2^53 limit?⌄
All outputs are stored in IEEE double. Values beyond 2^53 cannot be represented exactly, so RunMat rejects inputs larger than 2^53 to avoid duplicate entries.
Does the GPU path stay device-resident?⌄
Yes—when a provider is active RunMat uploads the host permutation after it is generated. Providers that later add a dedicated permutation kernel can replace the fallback without changing user code.
Related Array functions
Creation
colon · createArray · empty · eye · false · full · inf · linspace · logspace · magic · meshgrid · nan · nchoosek · ndgrid · nonzeros · ones · peaks · perms · rand · randi · randn · 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 randperm is executed, line by line, in Rust.
- View the source for randperm 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.