Using the C++ Math Library    

Selecting a Vector

Use a vector index to select multiple elements from an array. For example,

selects the second, fifth and eighth elements of the matrix A:

Because the index is a 1-by-3 row vector, the result is also a 1-by-3 row vector.

The expression

selects the same elements of A, but returns the result as a column vector because vertcat() produced a column vector:

Specifying a Vector Index with end( )

Sometimes you don't know how large an array is in a particular dimension, but you want to perform an indexing operation that requires you to specify the last element in that dimension. In MATLAB, you can use the end function to refer to the last element in a given dimension.

For example, A(6:end) selects the elements from A(6) to the end of the array. The MATLAB C++ Math Library's end() function corresponds to the MATLAB end() function. Given an array, a dimension (1 = row, 2 = column, 3 = page, and so on), and the number of indices in the subscript, end() returns (as a 1-by-1 array) the index of the last element in the specified dimension. You can then use that scalar array to generate a vector index.

Given the row dimension for a vector or scalar array, end() returns the number of columns. Given the column dimension for a vector or scalar array, it returns the number of rows. For a matrix, end() treats the matrix as a vector and returns the number of elements in the matrix.

This C++ code selects all but the first five elements in matrix A, just as A(6:end) does in MATLAB.

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


 Selecting a Single Element Selecting a Matrix