MATLAB Function Reference
sub2ind

Single index from subscripts

Syntax

• ```IND = sub2ind(siz,I,J)
IND = sub2ind(siz,I1,I2,...,In)
```

Description

The `sub2ind` command determines the equivalent single index corresponding to a set of subscript values.

```IND = sub2ind(siz,I,J) ``` returns the linear index equivalent to the row and column subscripts `I` and `J` for a matrix of size `siz`. `siz` is a 2-element vector, where `siz(1)` is the number of rows and `siz(2)` is the number of columns.

```IND = sub2ind(siz,I1,I2,...,In) ``` returns the linear index equivalent to the `n` subscripts `I1`,`I2`,...,`In` for an array of size `siz`. `siz` is an `n`-element vector that specifies the size of each array dimension.

Examples

Create a 3-by-4-by-2 array, `A`.

• ```A = [17 24 1 8; 2 22 7 14; 4 6 13 20];
A(:,:,2) = A - 10

A(:,:,1) =

17    24     1     8
2    22     7    14
4     6    13    20

A(:,:,2) =

7    14    -9    -2
-8    12    -3     4
-6    -4     3    10
```

The value at row 2, column 1, page 2 of the array is -8.

• ```A(2,1,2)

ans =

-8
```

To convert `A(2,1,2)` into its equivalent single subscript, use `sub2ind`.

• ```sub2ind(size(A),2,1,2)

ans =

14
```

You can now access the same location in `A` using the single subscripting method.

• ```A(14)

ans =

-8
```

`ind2sub`, `find`, `size`