sub2ind — Convert N-D subscript coordinates into MATLAB-style column-major linear indices.
sub2ind(sz, s1, s2, ...) maps row/column or higher-dimensional subscripts into linear indices using MATLAB column-major ordering. The size vector sz defines target extents and each dimension requires a matching subscript input.
Syntax
ind = sub2ind(sz, I1, In...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
sz | SizeArg | Yes | — | Size vector describing source array dimensions. |
I1 | Any | Yes | — | First-dimension subscript values. |
In | Any | Variadic | — | Remaining per-dimension subscript arrays/scalars. |
Returns
| Name | Type | Description |
|---|---|---|
ind | NumericArray | Column-major linear indices corresponding to provided subscripts. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:sub2ind:InvalidInput | Size vector, subscript count, or subscript types are invalid. | sub2ind: invalid input arguments |
RunMat:sub2ind:IndexBounds | At least one subscript lies outside bounds for its dimension. | sub2ind: subscript index exceeds dimension bounds |
RunMat:sub2ind:ProviderError | GPU provider sub2ind hook fails. | sub2ind: provider execution failed |
RunMat:sub2ind:InternalError | Internal tensor conversion/output construction fails. | sub2ind: internal error |
How sub2ind works
- Subscripts can be scalars or arrays. When arrays are provided, they must share the same size. Scalars broadcast to that common shape.
- All subscripts must be positive integers within the corresponding dimension's range.
- The size vector can be a row or column vector. Each element must be a positive integer.
- Complex, NaN, or infinite values are rejected.
- The result uses the same shape as the subscript arrays. Scalars produce a scalar double.
- When any input is a GPU tensor, RunMat computes on the host (to reuse integer semantics) and uploads the resulting indices back to the GPU so fusion and downstream kernels keep operating on device.
Does RunMat run sub2ind on the GPU?
When a WGPU-backed provider is active, sub2ind executes entirely on the GPU. The shader mirrors MATLAB's validation rules: it rejects non-finite values, non-integer subscripts, and out-of-range indices, surfacing the same diagnostic messages as the CPU path. Providers that do not yet implement the hook fall back to the host implementation; after the indices are computed they are uploaded back to the active provider so downstream fused kernels continue operating on device data.
GPU memory and residency
rows = gpuArray((1:100)');
cols = gpuArray(ones(100, 1) * 4);
idx = sub2ind([100 4], rows, cols);Expected behavior:
% idx remains a gpuArray containing the column-major indices.
disp(gather(idx(1:5)));
% Output:
% 301
% 302
% 303
% 304
% 305Examples
Converting a single matrix subscript to a linear index
idx = sub2ind([3 4], 2, 3)Expected output:
idx = 8Mapping multiple subscripts into one-dimensional indices
rows = [1; 2; 3];
cols = [3; 3; 3];
idx = sub2ind([3 5], rows, cols)Expected output:
idx =
7
8
9Handling higher-dimensional array subscripts
row = [1 1];
col = [2 3];
page = [1 2];
idx = sub2ind([2 3 4], row, col, page)Expected output:
idx = [3 11]Broadcasting scalar subscripts across array inputs
rows = [1 2 3];
idx = sub2ind([3 4], rows, 4)Expected output:
idx = [10 11 12]Retaining GPU residency for batched index conversions
rows = gpuArray((1:100)');
cols = gpuArray(ones(100, 1) * 4);
idx = sub2ind([100 4], rows, cols)Expected output:
% idx remains a gpuArray containing the column-major indices.
disp(gather(idx(1:5)));
% Output:
% 301
% 302
% 303
% 304
% 305Detecting invalid out-of-range subscripts
try
idx = sub2ind([3 4], 4, 1);
catch ME
disp(ME.message);
endExpected output:
Index exceeds the number of rows in dimension 1.Using sub2ind with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how sub2ind changes the result.
Run a small sub2ind example, explain the result, then change one input and compare the output.
FAQ
What data types does sub2ind accept?⌄
Numeric and logical inputs are accepted. Logical values are converted to doubles before validation. Complex, NaN, and infinite values are rejected with a descriptive error.
Can the size vector contain zeros?⌄
No. Every dimension size must be a positive integer. This matches MATLAB's behavior for index conversion.
Do subscripts have to be the same size?⌄
Yes. All non-scalar subscripts must share the same size (shape). Scalars broadcast to that common shape.
What happens when subscripts are out of range?⌄
sub2ind throws an error explaining which dimension failed the bounds check. This mirrors MATLAB's run-time error.
Does the function support GPU arrays?⌄
Yes. With the WGPU provider the conversion happens entirely on device, including validation. Other providers gather the data to the host, compute the indices, and upload them back to the device automatically.
Are fractional subscripts rounded?⌄
No. Non-integer, NaN, or infinite subscripts raise an error.
How is the linear index computed?⌄
The output uses MATLAB's column-major convention: 1 + sum((s_k - 1) * stride_k) where stride_k is the product of the preceding dimensions.
Can I call sub2ind with more subscripts than dimensions?⌄
No. You must pass exactly one subscript per dimension listed in the size vector.
What about empty outputs?⌄
If the subscript arrays are empty, sub2ind returns an empty double array with the same shape.
Does sub2ind change the orientation of row/column vectors?⌄
No. The output preserves the orientation (shape) of the subscript arrays, so row vectors stay row vectors and column vectors stay column vectors.
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 sub2ind is executed, line by line, in Rust.
- View the source for sub2ind 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.