#### 8.1.1 Advanced Indexing

An array with ‘`n`’ dimensions can be indexed using ‘`m`’ indices. More generally, the set of index tuples determining the result is formed by the Cartesian product of the index vectors (or ranges or scalars).

For the ordinary and most common case, `m == n`, and each index corresponds to its respective dimension. If `m < n` and every index is less than the size of the array in the i^{th} dimension, `m(i) < n(i)`, then the index expression is padded with trailing singleton dimensions (`[ones (m-n, 1)]`). If `m < n` but one of the indices `m(i)` is outside the size of the current array, then the last `n-m+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 (m == n): ans = 6
    a(2,1);     # Case (m < n), idx within array:
                # equivalent to a(2,1,1), ans = 2
    a(2,4);     # Case (m < n), 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.

Function File: ind = sub2ind (dims, i, j)
Function File: ind = sub2ind (dims, s1, s2, …, sN)

  Convert subscripts to a linear index.

  The following example shows how to convert the two-dimensional index `(2,3)` of a 3-by-3 matrix to a linear index. The matrix is linearly indexed moving from one column to next, filling up all rows in each column.

      linear_index = sub2ind ([3, 3], 2, 3)
      ⇒ 8

  See also: ind2sub.

Function File: [s1, s2, …, sN] = ind2sub (dims, ind)

  Convert a linear index to subscripts.

  The following example shows how to convert the linear index `8` in a 3-by-3 matrix into a subscript. The matrix is linearly indexed moving from one column to next, filling up all rows in each column.

      [r, c] = ind2sub ([3, 3], 8)
          ⇒ r =  2
          ⇒ c =  3

  See also: sub2ind.

Built-in Function: isindex (ind)
Built-in Function: 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.

Built-in Function: val = allow_noninteger_range_as_index ()
Built-in Function: old_val = allow_noninteger_range_as_index (new_val)
Built-in Function: 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.