Skip to main content

5.9) Linear Indices


An alternative way of accessing elements of a matrix is using linear indices rather than dimensional subscripts. For example:

[matlab]
>> d=rand(4,4)
>> d(2,3) % using subscripts
>> d(10) % using a linear index
[/matlab]

The linear index counts down the rows (first dimension) of the first column, then moves gradually along the columns (second dimension), then along subsequent dimensions (if any).

  • Linear indices refer to how Matlab stores arrays in memory. They are not often used - and can be the cause of difficult-to-find bugs
  • But in some circumstances, using linear indices may be faster than using subscripts.
  • One can move from linear indices to subscripts (and vice versa) using the functions "ind2sub" and "sub2ind".