Linear Indexing Example

From MATLAB Techniques for Image Processing by Steve Eddins.

Make a 5-by-5 matrix:

A = magic(5)
A =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

POP QUIZ: What does this do?

A(17)
ans =

    14

MATLAB interprets a single subscript as an index into a long vector containing all the values of A in column order. So A(17) is the same as A(2, 4).

A(2,4)
ans =

    14

This is called linear indexing.

So what's the connection to image processing? Suppose A is our image, and some previous computation has told us that we are interested in the pixel values at these row and column coordinates:

row = [2 1 5];
col = [1 3 4];

Can we extract the desired pixel values in a single expression? Let's try:

A(row,col)
ans =

    23     7    14
    17     1     8
    11    25     2

Well, we got nine values out, not three, so that certainly isn't what we are looking for. MATLAB computes A(row, col) as the submatrix of A formed by the intersections of the specified rows and columns.

Instead of indexing into A using row and column subscripts, we need to index using a single subscript.

Here's how to convert from row-column subscripts into linear indices:

M = size(A,1);
idx = M*(col - 1) + row
idx =

     2    11    20

The expression A(idx) pulls out just the three values we want:

A(idx)
ans =

    23     1     2

Or we can assign to just those elements:

A(idx) = Inf
A =

    17    24   Inf     8    15
   Inf     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25   Inf     9

The functions sub2ind ("subscript" to "index") and ind2sub convert back and forth between row-column subscripts and linear indices.

idx = sub2ind(size(A),row,col)
idx =

     2    11    20

[r,c] = ind2sub(size(A),idx)
r =

     2     1     5


c =

     1     3     4