sub2indConverting subscripts to linear index
I = sub2ind(sizVec, sub1, sub2, ..., subN)sizVec is a size vector.sub1, sub2, ..., subN are arrays with identical sizes, which contain subscripts of dimensions 1, 2, ..., N, respectively.I contains the corresponding linear indexes and has the same size as subi.i-th element of I is obtained from the subscripts [sub1(i), sub2(i), ..., subN(i)] as shown in the following figure.
Depending on the ndims of sizVec and N, the function has different behaviours:
ndims == N, e.g., sub2ind([2,3,4],1,2,3), then sizVec is used directly to obtain the linear indices.ndims < N, e.g., sub2ind([2,3,4],1,2,3,1), then ones are appended to the end of sizVec to form a new size vector of length equal to N. The new size vector is then used to obtain the linear indices.ndims > N > 1, e.g., sub2ind([2 3 4 5],1,2), then sizVec is reshaped to a new size vector having N dimensions. More specifically, the new size vector is [sizVec(1:N - 1) prod(sizVec(N:end))]. The new size vector is then used to obtain the linear indices.N == 1, then sub1 in sub2ind(sizVec,sub1) will be treated as linear indices. As a result, sub1 will be returned directly.I1 is first converted to subscript arrays s1 and s2. Then, s1 and s2 are converted back to linear index array I2. As expected, I1 is equal to I2.I1 = randi(10,1,5)
[s1, s2] = ind2sub([2 5], I1)
I2 = sub2ind([2 5], s1, s2)
I1 =
3.0000 3.0000 4.0000 10.000 4.0000
s1 =
1.0000 1.0000 2.0000 2.0000 2.0000
s2 =
2.0000 2.0000 2.0000 5.0000 2.0000
I2 =
3.0000 3.0000 4.0000 10.000 4.0000