linearInd = sub2ind(matrixSize, rowSub, colSub) returns the linear index equivalents to the row and column subscripts rowSub andcolSub for a matrix of size matrixSize. The matrixSize input is a 2-element vector that specifies the number of rows and columns in the matrix as [nRows, nCols]. The rowSub and colSub inputs are positive, whole number scalars or vectors that specify one or more row-column subscript pairs for the matrix. Example 3 demonstrates the use of vectors for the rowSub and colSub inputs.
Examples
Example 1
This example converts the subscripts (2, 1, 2) for three-dimensional array A to a single linear index. Start by creating a 3-by-4-by-2 array A:
rand('state', 0); % Initialize random number generator.
A = rand(3, 4, 2)
A(:,:,1) =
0.9501 0.4860 0.4565 0.4447
0.2311 0.8913 0.0185 0.6154
0.6068 0.7621 0.8214 0.7919
A(:,:,2) =
0.9218 0.4057 0.4103 0.3529
0.7382 0.9355 0.8936 0.8132
0.1763 0.9169 0.0579 0.0099
Find the linear index corresponding to (2, 1, 2):
linearInd = sub2ind(size(A), 2, 1, 2)
linearInd =
14
Make sure that these agree:
A(2, 1, 2) A(14)
ans = and =
0.7382 0.7382
Example 2
Using the 3-dimensional array A defined in the previous example, specify only 2 of the 3 subscript arguments in the call to sub2ind. The third subscript argument defaults to 1.
The command
linearInd = sub2ind(size(A), 2, 4)
ans =
11
is the same as
linearInd = sub2ind(size(A), 2, 4, 1)
ans =
11
Example 3
Using the same 3-dimensional input array A as in Example 1, accomplish the work of five separate sub2ind commands with just one.
Replace the following commands:
sub2ind(size(A), 3, 3, 2);
sub2ind(size(A), 2, 4, 1);
sub2ind(size(A), 3, 1, 2);
sub2ind(size(A), 1, 3, 2);
sub2ind(size(A), 2, 4, 1);
with a single command:
sub2ind(size(A), [3 2 3 1 2], [3 4 1 3 4], [2 1 2 2 1])
ans =
21 11 15 19 11
Verify that these linear indices access the same array elements as their subscripted counterparts:
[A(3,3,2), A(2,4,1), A(3,1,2), A(1,3,2), A(2,4,1)]
ans =
0.0579 0.6154 0.1763 0.4103 0.6154
A([21, 11, 15, 19, 11])
ans =
0.0579 0.6154 0.1763 0.4103 0.6154