Skip to content

sub2ind

Converting subscripts to a linear index

I = sub2ind(sizVec, sub1, sub2, ..., subN)

  • sizVec is a size vector of length N.
  • sub1, sub2, ..., subN are scalars or vectors containing subscripts of dimensions 1, 2, ..., N, respectively.
  • I contains the corresponding linear indexes

Example 1: Linear index array 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 =
 7.000   5.000   1.000   4.000   4.000

s1 =
 1.000   1.000   1.000   2.000   2.000

s2 =
 4.000   3.000   1.000   2.000   2.000

I2 =
 7.000   5.000   1.000   4.000   4.000