octave: Advanced Indexing
8.1.1 Advanced Indexing
-----------------------
An array with ‘nd’ dimensions can be indexed by a vector IDX which has
from 1 to ‘nd’ elements. If any element of IDX is not a scalar then the
complete set of index tuples will be generated from the Cartesian
product of the index elements.
For the ordinary and most common case, the number of indices (‘nidx =
numel (IDX)’) matches the number of dimensions ‘nd’. In this case, each
element of IDX corresponds to its respective dimension, i.e., ‘IDX(1)’
refers to dimension 1, ‘IDX(2)’ refers to dimension 2, etc. If
‘nidx < nd’, and every index is less than the size of the array in the
i^{th} dimension (‘IDX(i) < size (ARRAY, i)’), then the index expression
is padded with ‘nd - nidx’ trailing singleton dimensions. If
‘nidx < nd’ but one of the indices ‘IDX(i)’ is outside the size of the
current array, then the last ‘nd - nidx + 1’ dimensions are folded into
a single dimension with an extent equal to the product of extents of the
original dimensions. This is easiest to understand with an example.
A = reshape (1:8, 2, 2, 2) # Create 3-D array
A =
ans(:,:,1) =
1 3
2 4
ans(:,:,2) =
5 7
6 8
A(2,1,2); # Case (nidx == nd): ans = 6
A(2,1); # Case (nidx < nd), idx within array:
# equivalent to A(2,1,1), ans = 2
A(2,4); # Case (nidx < nd), idx outside array:
# Dimension 2 & 3 folded into new dimension of size 2x2 = 4
# Select 2nd row, 4th element of [2, 4, 6, 8], ans = 8
One advanced use of indexing is to create arrays filled with a single
value. This can be done by using an index of ones on a scalar value.
The result is an object with the dimensions of the index expression and
every element equal to the original scalar. For example, the following
statements
a = 13;
a(ones (1, 4))
produce a vector whose four elements are all equal to 13.
Similarly, by indexing a scalar with two vectors of ones it is
possible to create a matrix. The following statements
a = 13;
a(ones (1, 2), ones (1, 3))
create a 2x3 matrix with all elements equal to 13.
The last example could also be written as
13(ones (2, 3))
It is more efficient to use indexing rather than the code
construction ‘scalar * ones (N, M, ...)’ because it avoids the
unnecessary multiplication operation. Moreover, multiplication may not
be defined for the object to be replicated whereas indexing an array is
always defined. The following code shows how to create a 2x3 cell array
from a base unit which is not itself a scalar.
{"Hello"}(ones (2, 3))
It should be, noted that ‘ones (1, n)’ (a row vector of ones) results
in a range (with zero increment). A range is stored internally as a
starting value, increment, end value, and total number of values; hence,
it is more efficient for storage than a vector or matrix of ones
whenever the number of elements is greater than 4. In particular, when
‘r’ is a row vector, the expressions
r(ones (1, n), :)
r(ones (n, 1), :)
will produce identical results, but the first one will be significantly
faster, at least for ‘r’ and ‘n’ large enough. In the first case the
index is held in compressed form as a range which allows Octave to
choose a more efficient algorithm to handle the expression.
A general recommendation, for a user unaware of these subtleties, is
to use the function ‘repmat’ for replicating smaller arrays into bigger
ones.
A second use of indexing is to speed up code. Indexing is a fast
operation and judicious use of it can reduce the requirement for looping
over individual array elements which is a slow operation.
Consider the following example which creates a 10-element row vector
a containing the values a(i) = sqrt (i).
for i = 1:10
a(i) = sqrt (i);
endfor
It is quite inefficient to create a vector using a loop like this. In
this case, it would have been much more efficient to use the expression
a = sqrt (1:10);
which avoids the loop entirely.
In cases where a loop cannot be avoided, or a number of values must
be combined to form a larger matrix, it is generally faster to set the
size of the matrix first (pre-allocate storage), and then insert
elements using indexing commands. For example, given a matrix ‘a’,
[nr, nc] = size (a);
x = zeros (nr, n * nc);
for i = 1:n
x(:,(i-1)*nc+1:i*nc) = a;
endfor
is considerably faster than
x = a;
for i = 1:n-1
x = [x, a];
endfor
because Octave does not have to repeatedly resize the intermediate
result.
-- : IND = sub2ind (DIMS, I, J)
-- : IND = sub2ind (DIMS, S1, S2, ..., SN)
Convert subscripts to linear indices.
The input DIMS is a dimension vector where each element is the size
of the array in the respective dimension (size XREFsize.).
The remaining inputs are scalars or vectors of subscripts to be
converted.
The output vector IND contains the converted linear indices.
Background: Array elements can be specified either by a linear
index which starts at 1 and runs through the number of elements in
the array, or they may be specified with subscripts for the row,
column, page, etc. The functions ‘ind2sub’ and ‘sub2ind’
interconvert between the two forms.
The linear index traverses dimension 1 (rows), then dimension 2
(columns), then dimension 3 (pages), etc. until it has numbered
all of the elements. Consider the following 3-by-3 matrices:
[(1,1), (1,2), (1,3)] [1, 4, 7]
[(2,1), (2,2), (2,3)] ==> [2, 5, 8]
[(3,1), (3,2), (3,3)] [3, 6, 9]
The left matrix contains the subscript tuples for each matrix
element. The right matrix shows the linear indices for the same
matrix.
The following example shows how to convert the two-dimensional
indices ‘(2,1)’ and ‘(2,3)’ of a 3-by-3 matrix to linear indices
with a single call to ‘sub2ind’.
s1 = [2, 2];
s2 = [1, 3];
ind = sub2ind ([3, 3], s1, s2)
⇒ ind = 2 8
See also: ind2sub XREFind2sub, size XREFsize.
-- : [S1, S2, ..., SN] = ind2sub (DIMS, IND)
Convert linear indices to subscripts.
The input DIMS is a dimension vector where each element is the size
of the array in the respective dimension (size XREFsize.).
The second input IND contains linear indies to be converted.
The outputs S1, ..., SN contain the converted subscripts.
Background: Array elements can be specified either by a linear
index which starts at 1 and runs through the number of elements in
the array, or they may be specified with subscripts for the row,
column, page, etc. The functions ‘ind2sub’ and ‘sub2ind’
interconvert between the two forms.
The linear index traverses dimension 1 (rows), then dimension 2
(columns), then dimension 3 (pages), etc. until it has numbered
all of the elements. Consider the following 3-by-3 matrices:
[1, 4, 7] [(1,1), (1,2), (1,3)]
[2, 5, 8] ==> [(2,1), (2,2), (2,3)]
[3, 6, 9] [(3,1), (3,2), (3,3)]
The left matrix contains the linear indices for each matrix
element. The right matrix shows the subscript tuples for the same
matrix.
The following example shows how to convert the two-dimensional
indices ‘(2,1)’ and ‘(2,3)’ of a 3-by-3 matrix to linear indices
with a single call to ‘sub2ind’.
The following example shows how to convert the linear indices ‘2’
and ‘8’ in a 3-by-3 matrix into subscripts.
ind = [2, 8];
[r, c] = ind2sub ([3, 3], ind)
⇒ r = 2 2
⇒ c = 1 3
If the number of output subscripts exceeds the number of
dimensions, the exceeded dimensions are set to ‘1’. On the other
hand, if fewer subscripts than dimensions are provided, the
exceeding dimensions are merged into the final requested dimension.
For clarity, consider the following examples:
ind = [2, 8];
dims = [3, 3];
## same as dims = [3, 3, 1]
[r, c, s] = ind2sub (dims, ind)
⇒ r = 2 2
⇒ c = 1 3
⇒ s = 1 1
## same as dims = [9]
r = ind2sub (dims, ind)
⇒ r = 2 8
See also: ind2sub XREFind2sub, size XREFsize.
-- : isindex (IND)
-- : isindex (IND, N)
Return true if IND is a valid index.
Valid indices are either positive integers (although possibly of
real data type), or logical arrays.
If present, N specifies the maximum extent of the dimension to be
indexed. When possible the internal result is cached so that
subsequent indexing using IND will not perform the check again.
Implementation Note: Strings are first converted to double values
before the checks for valid indices are made. Unless a string
contains the NULL character "\0", it will always be a valid index.
-- : VAL = allow_noninteger_range_as_index ()
-- : OLD_VAL = allow_noninteger_range_as_index (NEW_VAL)
-- : allow_noninteger_range_as_index (NEW_VAL, "local")
Query or set the internal variable that controls whether
non-integer ranges are allowed as indices.
This might be useful for MATLAB compatibility; however, it is still
not entirely compatible because MATLAB treats the range expression
differently in different contexts.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it
calls. The original variable value is restored when exiting the
function.