ind2sub

Syntax

Description

[row,col] = ind2sub(sz,ind)
returns the arrays row and col containing the
equivalent row and column subscripts corresponding to the linear indices
ind for a matrix of size sz. Here
sz is a vector with two elements, where sz(1)
specifies the number of rows and sz(2) specifies the number of columns.

Convert Linear Indices to Subscripts for Three-Dimensional Array

Convert the linear indices [3 4 5 6] to subscripts in a 2-by-2-by-2 array. The mapping from linear indices to subscripts (indexing by position) for a 2-by-2-by-2 array can be illustrated as in the following.

Use ind2sub with Fewer Output Arguments

When using ind2sub for an N-dimensional array, you would typically supply N output arguments for each dimension of the matrix. This example shows the different results when you return fewer output arguments for a 3-dimensional array.

Create the input arguments needed to convert the linear indices 1 through 8 for a 3-dimensional array with size 2-by-2-by-2.

ind = 1:8;
sz = [2 2 2];

Specify three output arguments when using ind2sub to return the row, column, and page subscripts for the 2-by-2-by-2 array.

[row,col,page] = ind2sub(sz,ind)

row = 1×8
1 2 1 2 1 2 1 2

col = 1×8
1 1 2 2 1 1 2 2

page = 1×8
1 1 1 1 2 2 2 2

If you specify only two output arguments, ind2sub ignores the third dimension of the array and returns subscripts for a 2-dimensional array with size 2-by-4 instead.

[row,col] = ind2sub(sz,ind)

row = 1×8
1 2 1 2 1 2 1 2

col = 1×8
1 1 2 2 3 3 4 4

If you specify only one output argument, ind2sub ignores the second and third dimensions of the array and returns subscripts for a 1-dimensional array with size 1-by-8 instead.

Multidimensional subscripts, returned as a scalar, vector, matrix, or
multidimensional array. The size of each array I1,I2,…,In is the
same as the size of the input ind.

Data Types: double

Tips

To get the linear indices of matrix elements that satisfy a specific condition for
matrix A, you can use the find function with one
output argument. To get the subscript indices, use the find function
with two output arguments. For example, [row,col] =
ind2sub(size(A),find(A>5)) gives the same result as [row,col] =
find(A>5).

Algorithms

For an array A, if [I1,…,In] = ind2sub(size(A),ind),
then A(I1(k),…,In(k)) = A(ind(k)) for all k.

Extended Capabilities

Tall ArraysCalculate with arrays that have more rows than fit in memory.

This function fully supports tall arrays. For
more information, see Tall Arrays.

C/C++ Code GenerationGenerate C and C++ code using MATLAB® Coder™.

Usage notes and limitations:

The first argument must be a valid size vector. Size vectors for arrays with more
than intmax elements are not
supported.