# Linear indexing

Last week I posted an introduction to logical indexing. This week I want to continue with a brief discussion of linear indexing and its connection to image processing in MATLAB.

A = hilb(5)
A =

1.0000    0.5000    0.3333    0.2500    0.2000
0.5000    0.3333    0.2500    0.2000    0.1667
0.3333    0.2500    0.2000    0.1667    0.1429
0.2500    0.2000    0.1667    0.1429    0.1250
0.2000    0.1667    0.1429    0.1250    0.1111



POP QUIZ: What does the MATLAB expression A(17) mean?

A(17)
ans =

0.2000



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

A(2, 4)
ans =

0.2000



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 =

0.5000    0.2500    0.2000
1.0000    0.3333    0.2500
0.2000    0.1429    0.1250



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 =

0.5000    0.3333    0.1250



Or we can assign to just those elements:

A(idx) = Inf
A =

1.0000    0.5000       Inf    0.2500    0.2000
Inf    0.3333    0.2500    0.2000    0.1667
0.3333    0.2500    0.2000    0.1667    0.1429
0.2500    0.2000    0.1667    0.1429    0.1250
0.2000    0.1667    0.1429       Inf    0.1111



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



For a couple of detailed image processing examples illustrating linear indexing, see these previous posts:

Published with MATLAB® 7.5

|

### コメント

コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。