ind2sub — Convert linear indices to subscripts in MATLAB and RunMat.
ind2sub(siz, idx) converts 1-based column-major linear indices into per-dimension subscripts for arrays of size siz. Output arity and indexing behavior follow MATLAB semantics.
Syntax
subs = ind2sub(sz, ind)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
sz | SizeArg | Yes | — | Size vector describing source array dimensions. |
ind | Any | Yes | — | Linear indices to convert into per-dimension subscripts. |
Returns
| Name | Type | Description |
|---|---|---|
subs | Any | Cell array containing one subscript output per dimension. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:ind2sub:InvalidInput | Size vector or linear index inputs are malformed or unsupported. | ind2sub: invalid input arguments |
RunMat:ind2sub:IndexBounds | At least one provided linear index exceeds array element bounds. | ind2sub: index exceeds array bounds |
RunMat:ind2sub:ProviderError | Provider-side ind2sub execution fails or returns malformed outputs. | ind2sub: provider execution failed |
RunMat:ind2sub:InternalError | Internal tensor/materialization logic fails while building outputs. | ind2sub: internal error |
How ind2sub works
- The size vector
sizsupplies one extent per dimension. Each entry must be a positive integer. idxcan be a scalar or an array of any shape; every element must be a positive integer withinprod(siz).- The result is always a 1×N cell array (N is
numel(siz)). Each cell contains a double array that matches the shape ofidx. - Non-integer, complex, NaN, Inf, or out-of-range indices raise MATLAB-compatible errors.
- Empty inputs produce empty outputs with matching shapes.
- When called with multiple outputs (
[i,j,k] = ind2sub(...)) RunMat unpacks the cell array automatically, mirroring MATLAB semantics.
Does RunMat run ind2sub on the GPU?
When a WGPU-backed provider is active, ind2sub executes entirely on the GPU. The shader mirrors MATLAB's validation rules, rejecting non-integer, non-positive, or out-of-range indices with the same diagnostic messages as the CPU path. Providers that do not yet implement the hook fall back to the host implementation; after computing the subscripts RunMat uploads the results back to the active provider so downstream fused kernels continue operating on device-resident data.
GPU memory and residency
You typically do not need to convert tensors manually. When the active provider implements the ind2sub hook (WGPU today), the entire conversion stays on the GPU. Otherwise RunMat gathers the inputs, performs validation on the host, and uploads the resulting subscript arrays back to the device so downstream kernels or fusion plans can continue using them without additional gather calls.
Examples
Recovering row and column subscripts from a matrix index
[row, col] = ind2sub([3 4], 8)Expected output:
row = 2;
col = 3Extracting multiple matrix indices at once
idx = [7 8 9];
[rows, cols] = ind2sub([3 5], idx)Expected output:
rows = [1 2 3];
cols = [3 3 3]Converting indices for a 3-D volume
idx = [3 11];
[r, c, p] = ind2sub([2 3 4], idx)Expected output:
r = [1 1];
c = [2 3];
p = [1 2]Keeping indices on the GPU
rows = gpuArray([1; 2; 3]);
cols = gpuArray([4; 4; 4]);
lin = sub2ind([3 4], rows, cols);
subs = ind2sub([3 4], lin); % subs{1} and subs{2} remain gpuArray values
class(subs{1})
class(subs{2})Expected output:
ans =
'gpuArray'
ans =
'gpuArray'Using a single output cell for flexible unpacking
subs = ind2sub(size(magic(4)), 6:9);
% Access with subs{1}, subs{2}, ...Expected output:
subs =
1×2 cell array
{1×4 double} {1×4 double}Validating index ranges before reshaping
A = magic(4);
idx = 1:numel(A);
[i, j] = ind2sub(size(A), idx)Using ind2sub with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how ind2sub changes the result.
Run a small ind2sub example, explain the result, then change one input and compare the output.
FAQ
What types does ind2sub accept for idx?⌄
Numeric and logical inputs are accepted. Logical arrays are treated as double precision (with true → 1, false → 0); complex values are rejected.
Can siz contain zeros?⌄
No. Each element of siz must be a positive integer, matching MATLAB behaviour.
How are errors reported for invalid indices?⌄
Indices that are non-integer, non-positive, or exceed prod(siz) raise errors matching MATLAB's wording (e.g., "Index exceeds number of array elements. Index must not exceed …").
What shape do the output arrays have?⌄
Each output array matches the shape of idx. Scalars produce scalar doubles; vectors remain vectors; higher-dimensional shapes are preserved.
Does ind2sub support GPU arrays?⌄
Yes. With the WGPU provider the conversion happens entirely on the GPU, including validation. Other providers gather the data to the host, compute the subscripts, and upload them back to the device automatically.
Can I request fewer outputs than dimensions?⌄
Yes. In a multi-output context RunMat provides as many outputs as requested in order, just like MATLAB. Any additional dimensions are still available inside the single-output cell if you need them.
How does ind2sub relate to sub2ind?⌄
They are inverse operations: sub2ind turns subscripts into linear indices, while ind2sub recovers subscripts from those linear indices.
Does ind2sub allocate full copies of the outputs?⌄
Yes. Each subscript array is materialised as a dense double array matching the shape of idx, mirroring MATLAB semantics.
What happens with empty inputs?⌄
Empty index arrays produce empty subscript arrays with the same shape.
Can I use ind2sub with more dimensions than two?⌄
Definitely—ind2sub works for any number of dimensions represented in siz.
Related Array functions
Shape
cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · squeeze · tril · triu · vertcat
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how ind2sub is executed, line by line, in Rust.
- View the source for ind2sub 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.