Next: , Up: Expressions   [Contents][Index]

8.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 (2-D) and higher multi-dimensional arrays are indexed using either one index or N indices where N is the dimension of the array. When using a single index expression to index 2-D or higher data the elements of the array are taken in column-first order (like Fortran).

The output from indexing assumes the dimensions of the index expression. For example:

a(2)       # result is a scalar
a(1:2)     # result is a row vector
a([1; 2])  # result is 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(:)       # result is a column vector
a(:)'      # result is a row vector

The above two code idioms are often used in place of reshape when a simple vector, rather than an arbitrarily sized array, is needed.

Given the matrix

a = [1, 2; 3, 4]

all of the following expressions are equivalent and select the first row of the matrix.

a(1, [1, 2])  # row 1, columns 1 and 2
a(1, 1:2)     # row 1, columns in range 1-2
a(1, :)       # row 1, all columns

In index expressions the keyword end automatically refers to the last entry for a particular dimension. This magic index can also be used in ranges and typically eliminates the needs to call size or length to gather array bounds before indexing. For example:

a = [1, 2, 3, 4];

a(1:end/2)        # first half of a => [1, 2]
a(end + 1) = 5;   # append element
a(end) = [];      # delete element
a(1:2:end)        # odd elements of a => [1, 3]
a(2:2:end)        # even elements of a => [2, 4]
a(end:-1:1)       # reversal of a => [4, 3, 2 , 1]

Next: , Up: Expressions   [Contents][Index]