#### 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.

: 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 (see size). 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, size.

: [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 (see size). 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 = 
r = ind2sub (dims, ind)
⇒ r =  2   8
```

See also: ind2sub, size.

: 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.