RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact
  • License
  • Privacy

Learn

  • Docs
  • Blog
  • Benchmarks
  • RunMat vs MATLAB Online

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

RunMat™ is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

/
See all docs
Builtin Reference
    • find
    • ind2sub
    • sub2ind

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

NameTypeRequiredDefaultDescription
szSizeArgYes—Size vector describing source array dimensions.
I1AnyYes—First-dimension subscript values.
InAnyVariadic—Remaining per-dimension subscript arrays/scalars.

Returns

NameTypeDescription
indNumericArrayColumn-major linear indices corresponding to provided subscripts.

Errors

IdentifierWhenMessage
RunMat:sub2ind:InvalidInputSize vector, subscript count, or subscript types are invalid.sub2ind: invalid input arguments
RunMat:sub2ind:IndexBoundsAt least one subscript lies outside bounds for its dimension.sub2ind: subscript index exceeds dimension bounds
RunMat:sub2ind:ProviderErrorGPU provider sub2ind hook fails.sub2ind: provider execution failed
RunMat:sub2ind:InternalErrorInternal 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.
  • The size vector and every subscript accept int8, uint8, int16, uint16, int32, uint32, int64, and uint64; RunMat reads their authoritative values directly and performs checked column-major index arithmetic.
  • The result is always double. Floating-point resident subscripts use the provider hook where available, while integer resident inputs gather exactly and return a resident double result when the owner supports upload.

Does RunMat run sub2ind on the GPU?

When a WGPU-backed provider is active, supported floating-point subscript forms execute through the provider hook with bounds and integrality checks. Native integer resident inputs deliberately use the exact host path so int64 and uint64 subscripts retain their full precision; after computation, the documented double indices are uploaded back to the input owner when possible.

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
%    305

Examples

Converting a single matrix subscript to a linear index

idx = sub2ind([3 4], 2, 3)

Expected output:

idx = 8

Mapping 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
     9

Handling 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
%    305

Detecting invalid out-of-range subscripts

try
    idx = sub2ind([3 4], 4, 1);
catch ME
    disp(ME.message);
end

Expected 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?⌄

The size vector and subscripts accept single, double, logical, and all eight native integer classes. Native integers are validated from exact storage rather than converted through double; complex, NaN, and infinite values are rejected. The output class is double.

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. Supported floating-point resident forms use the provider hook. Integer resident forms use exact owner-aware gather fallback, then upload the double result when possible. This automatic residency handling does not require an extension setting.

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

Indexing

find · ind2sub

Grouping

accumarray · combinations · discretize · findgroups · groupcounts · grp2idx · splitapply

Sorting Sets

argsort · intersect · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sort · sortrows · union · unique

Shape

blkdiag · cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · squeeze · toeplitz · tril · triu · vertcat

Creation

colon · createArray · empty · eye · false · full · inf · linspace · logspace · magic · meshgrid · nan · nchoosek · ndgrid · nonzeros · ones · peaks · perms · rand · randi · randn · randperm · range · sparse · spdiags · speye · spones · sprand · true · zeros

Introspection

iscolumn · isempty · ismatrix · isrow · isscalar · isvector · length · ndims · numel · size

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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • How sub2ind works
  • Does RunMat run sub2ind on the GPU?
  • GPU memory and residency
  • Examples
  • Converting a single matrix subscript to a linear index
  • Mapping multiple subscripts into one-dimensional indices
  • Handling higher-dimensional array subscripts
  • Broadcasting scalar subscripts across array inputs
  • Retaining GPU residency for batched index conversions
  • Detecting invalid out-of-range subscripts
  • Using sub2ind with coding agents
  • FAQ
  • Related Array functions
  • Indexing
  • Grouping
  • Sorting Sets
  • Shape
  • Creation
  • Introspection
  • Open-source implementation
  • About RunMat