sub2ind
Converts row and column subscripts to linear indices.
Category: Language Fundamentals > Matrices and Arrays
Syntax
ind = sub2ind(sz, I, J)
Returns the linear index of element (I,J) in an array of size sz.
ind = sub2ind(sz, I1, I2, ..., In)
Same for an N-dimensional array.
Description
MATLAB stores arrays column by column, so the element at row i and column j of an m-row matrix has linear index i + (j-1)*m. sub2ind applies that rule for any number of dimensions and checks that the subscripts are in range.
It is handy for picking scattered elements, such as a diagonal or a list of points, with a single index vector.
Input arguments
sz- Size vector of the array, for example
[3 4]. I, J- Subscript arrays of identical size. Each value must be a positive integer within the matching dimension of
sz.
Output arguments
ind- Linear indices, same size as the subscript arguments.
Example
M = magic(4);
k = sub2ind(size(M), [1 2 3], [2 3 4])
M(k)
Output
k = 1×3
5 10 15
ans = 1×3
2 10 12