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 index expression. Matrices may be indexed using one or two indices. When using a single index expression, the elements of the matrix are taken in column-first order; the dimensions of the output match those of the index expression. For example,

     a (2)       # a scalar
     a (1:2)     # a row vector
     a ([1; 2])  # a column vector

As a special case, when a colon is used as a single index, the output is a column vector containing all the elements of the vector or matrix. For example

     a (:)       # a column vector

A warning is issued when using a single expression to index a matrix, unless the value of the built-in variable warn_fortran_indexing is zero.

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.

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.