Next: , Up: Expressions


10.1 Index Expressions

An index expression allows you to reference or extract selected elements of a matrix or vector.

Indices may be scalars, vectors, ranges, or the special operator `:', which may be used to select entire rows or columns.

Vectors are indexed using a single expression. Matrices may be indexed using one or two indices (a warning is issued if a single index is used unless the value of the built-in variable warn_fortran_indexing is zero).

— Built-in Variable: warn_fortran_indexing

If the value of warn_fortran_indexing is nonzero, a warning is printed for expressions which select elements of a two-dimensional matrix using a single index. The default value is 0.

Given the matrix

     a = [1, 2; 3, 4]

all of the following expressions are equivalent

     a (1, [1, 2])
     a (1, 1:2)
     a (1, :)

and select the first row of the matrix.

Indexing a scalar with a vector of ones can be used to create a vector the same size as the index vector, with each element equal to the value of the original scalar. For example, the following statements

     a = 13;
     a ([1, 1, 1, 1])

produce a vector whose four elements are all equal to 13.

Similarly, indexing a scalar with two vectors of ones can be used to create a matrix. For example the following statements

     a = 13;
     a ([1, 1], [1, 1, 1])

create a 2 by 3 matrix with all elements equal to 13.

This is an obscure notation and should be avoided. It is better to use the function ones to generate a matrix of the appropriate size whose elements are all one, and then to scale it to produce the desired result. See Special Utility Matrices.

— Built-in Variable: warn_resize_on_range_error

If the value of warn_resize_on_range_error is nonzero, print a warning when a matrix is resized by an indexed assignment with indices outside the current bounds. The default value is 0.

Note that it is quite inefficient to create a vector using a loop like the one shown in the example above. In this particular case, it would have been much more efficient to use the expression

     a = sqrt (1:10);

thus avoiding the loop entirely. In cases where a loop is still required, or a number of values must be combined to form a larger matrix, it is generally much faster to set the size of the matrix first, 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

particularly for large matrices because Octave does not have to repeatedly resize the result.