Using the C++ Math Library    

Selecting a Vector of Elements

Use a scalar index with either a vector or a matrix index to extract a vector of elements from a matrix. You can use the function horzcat(), vertcat(), or colon() to make the vector or matrix index, or use an mwArray variable that contains a vector or matrix.

The indexing routines iterate over the vector index, pairing each element of the vector with the scalar index. Think of this process as applying a (scalar, scalar) subscript multiple times; the result of each selection is collected into a vector. The indexing code iterates down the columns of the matrix index in exactly the same way it iterates over a vector index.

For example, A(horzcat(1,3), 2) selects the first and third element (or first and third rows) of column 2:

In MATLAB A([1 3], 2) performs the same operation.

If you reverse the positions of the indices, A(2, horzcat(1, 3)), you select the first and third element (or first and third columns) of row 2:

If the vector index repeats a number, the same element is extracted multiple times. For example, A(2, horzcat(3, 3)) returns two copies of the element at A(2,3):

Specifying a Vector Index with end( )

The end() function, which corresponds to the MATLAB end() function, provides another way of specifying a vector index. Given an array, a dimension (1 = row, 2 = column, 3 = page, and so on), and the number of indices in the subscript, end() returns the index of the last element in the specified dimension. You then use that scalar array to generate a vector index. See Specifying a Vector Index with end( ) for a more complete description of how and why you use the end function in MATLAB.

Given the row dimension, end() returns the number of columns. Given the column dimension, it returns the number of rows.

This code selects all but the first element in row 3:

just as

does in MATLAB.

The second argument end(), 2, identifies the dimension where end() is used, here the column dimension. The third argument, 2, indicates the number of indices in the subscript; for two-dimensional indexing, it is always 2. This code selects these elements from matrix A:

Selecting a Row or Column

Use the colon() index and a scalar index to select an entire row or column. For example, A(1, colon()) selects the first row:

A(colon(), 2) selects the second column:


 Selecting a Single Element Selecting a Matrix