16.1 Multiple Indexing
The following is the simplest concrete example of multiple indexing with an array of integers; the ellipses stand for code defining the variables as indicated in the comments.
int c[3];
... // define: c == (5, 9, 7)
int idxs[4];
... // define: idxs == (3, 3, 1, 2)
int d[4];
d = c[idxs]; // result: d == (7, 7, 5, 9)
In general, the multiple indexed expression c[idxs]
is defined
as follows, assuming idxs
is of size K
.
c[idxs] = ( c[idxs[1]], c[idxs[2]], ..., c[idxs[K]] )
Thus c[idxs]
is of the same size as idxs
, which is
K
in this example.
Multiple indexing can also be used with multi-dimensional arrays. For example, consider the following.
int c[2, 3];
... // define: c = ((1, 3, 5), ((7, 11, 13))
int idxs[4];
... // define: idxs = (2, 2, 1, 2)
int d[4, 3]
d = c[idxs]; // result: d = ((7, 11, 13), (7, 11, 13),
// (1, 3, 5), (7, 11, 13))
That is, putting an index in the first position acts exactly the same
way as defined above. The fact that the values are themselves arrays
makes no difference—the result is still defined by c[idxs][j] == c[idxs[j]]
.
Multiple indexing may also be used in the second position of a multi-dimensional array. Continuing the above example, consider a single index in the first position and a multiple index in the second.
int e[4];
e = c[2, idxs]; // result: c[2] = (7, 11, 13)
// result: e = (11, 11, 7, 11)
The single index is applied, the one-dimensional result is determined,
then the multiple index is applied to the result. That is,
c[2,idxs]
evaluates to the same value as c[2][idxs]
.
Multiple indexing can apply to more than one position of a multi-dimensional array. For instance, consider the following
int c[2, 3];
... // define: c = ((1, 3, 5), (7, 11, 13))
int idxs1[3];
... // define: idxs1 = (2, 2, 1)
int idxs2[2];
... // define: idxs2 = (1, 3)
int d[3, 2];
d = c[idxs1, idxs2]; // result: d = ((7, 13), (7, 13), (1, 5))
With multiple indexes, we no longer have c[idxs1,~idxs2]
being
the same as c[idxs1][idxs2]
. Rather, the entry d[i,~j]
after executing the above is given by
d[i, j] == c[idxs1, idxs2][i, j] = c[idxs1[i], idxs2[j]]
This example illustrates the operation of multiple indexing in the
general case: a multiple index like idxs1
converts an index
i
used on the result (here, c[idxs1, idxs2]
) to index
idxs1[i]
in the variable being indexed (here, c
). In
contrast, a single index just returns the value at that index, thus
reducing dimensionality by one in the result.