ind2sub

Converts linear indices to row, column and higher subscripts.

Category: Language Fundamentals > Matrices and Arrays

Syntax

[r, c] = ind2sub(sz, ind)

Subscripts for a matrix of size sz.

[i1, i2, ..., iN] = ind2sub(sz, ind)

One subscript per dimension.

Description

MATLAB stores arrays down the columns, so index 1 to m is the first column of an m-row matrix, and so on. ind2sub undoes that numbering, which is what you need after find or max returned a position in the flattened array. sub2ind is the inverse.

If fewer outputs are requested than the array has dimensions, the last output absorbs the remaining ones.

Input arguments

sz
Size vector of the array, such as [3 4] or size(A).
ind
Linear index (or array of indices) in column-major order.

Output arguments

r, c, ...
Subscript arrays, each the same size as ind.

Example

Back to subscripts

[r, c] = ind2sub([2 3], [1 4 6])
[r, c, p] = ind2sub([2 3 2], 11)
Output
r = 1×3

     1     2     2
c = 1×3

     1     2     3
r = 1
c = 3
p = 2

Notes

An index beyond the array size is not reported as an error in MatLivre.

See also

sub2ind find size max