ind2subConverting a linear index to subscripts
[s1, s2, ..., sN] = ind2sub(sizVec, I)sizVec is a size vector.I is an array containing linear indexes for the size vector sizVec. Each element of I is converted to subscripts s1, s2, ..., sN for the size vector sizVec.s1, s2, ..., sN have the same sizes as I, as illustrated in the figure below.
Depending on the ndims of sizVec and N, the function has different behaviours:
ndims == N, e.g., [s1,s2,s3] = ind2sub([2,3,4],3), then I is converted using sizVec.ndims < N, e.g., [s1,s2,s3] = sub2ind([2,3],3), then I is converted using sizVec and then si for i larger than ndims are all ones.ndims > N > 1, e.g., [s1, s2] = sub2ind([2 3 4 5],20), 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 subscripts.N == 1, calling sub2ind(sizVec,I) directly returns I.I = randi(10,3,3)
[s1, s2] = ind2sub([2 5], I)
I =
7.000 4.000 8.000
5.000 9.000 6.000
2.000 2.000 6.000
s1 =
1.000 2.000 2.000
1.000 1.000 2.000
2.000 2.000 2.000
s2 =
4.000 2.000 4.000
3.000 5.000 3.000
1.000 1.000 3.000